简单的java代码
用java代码写的简易计算器(可以实现基本的加减乘除功能)

⽤java代码写的简易计算器(可以实现基本的加减乘除功能)package A;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.*;public class Calcular3 extends JFrame implements ActionListener,MouseListener{private int m1=0,n=0;//private double m2=0;//运算的数private int flag=0;JFrame f;JPanel p1,p2,p3;JTextField t;JButton b1[]=new JButton[18];String b[]= {"1","2","3","4","5","6","7","8","9","0","清空","退格",".","=","+","-","*","/"};public Calcular3(){f=new JFrame("计算器");t=new JTextField(35);p1=new JPanel();p2=new JPanel();p3=new JPanel();f.setBounds(100, 100, 400, 200);f.add(p1,BorderLayout.NORTH);f.add(p2,BorderLayout.CENTER);f.add(p3,BorderLayout.EAST);p2.setLayout(new GridLayout(5,3));p3.setLayout(new GridLayout(4,1));p1.add(t);for(int i=0;i<14;i++) {b1[i]=new JButton(b[i]);p2.add(b1[i]);b1[i].addActionListener(this);}for(int i=14;i<18;i++) {b1[i]=new JButton(b[i]);p3.add(b1[i]);b1[i].addActionListener(this);}/*for(int i=0;i<18;i++) {b1[i].addActionListener(this);}*/f.setVisible(true);}//实现接⼝的⽅法public void mouseClicked(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void actionPerformed(ActionEvent e) {String str="";int i;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {if(i==9) {n=n*10;}else {n=n*10+i+1;}str=String.valueOf(n);//整形n转换成字符串strt.setText(str);//显⽰到⽂本框上}}for(i=14;i<18;i++) {//+、-、*、/if(e.getSource()==b1[i]) {//匹配运算符m1=Integer.parseInt(t.getText());if(flag==15) {m2=m1+m2;}else if(flag==16) {m2=m1-m2;}else if(flag==17) {m2=m1*m2;}else if(flag==18) {m2=m1/m2;}else m2=m1;//若⽆连续的运算符运算,保存当前数据到m2 if(i==14) flag=15;else if(i==15) flag=16;else if(i==16) flag=17;else flag=18;str=String.valueOf(b[i]);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据break;//找到匹配数据退出循环}}if(e.getSource()==b1[13]) {//=m1=Integer.parseInt(t.getText());if(flag==15) {m2=m2+m1;}else if(flag==16) {m2=m2-m1;}else if(flag==17) {m2=m2*m1;}else if(flag==18) {m2=m2/m1;}else m2=m1;str=String.valueOf(m2);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据flag=0;//flag还原0,表明没有未处理的运算符}if(e.getSource()==b1[10]) {//各变量变为0 清空m1=0;m2=0;flag=0;n=0;t.setText("0");//显⽰到⽂本框上}if(e.getSource()==b1[11]) {//退格m1=(int)(Double.parseDouble(t.getText())/10);n=m1;str=String.valueOf(m1);t.setText(str);}if(e.getSource()==b1[12]) {//⼩数点m1=Integer.parseInt(t.getText());str=String.valueOf(m1+b[12]);t.setText(str);//显⽰到⽂本框上int j=0;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {j++;m2=Math.pow(0.1, j)*Integer.parseInt(b[i]);str=String.valueOf(m1+m2);t.setText(str);//显⽰到⽂本框上}}}}//主函数public static void main(String[] args) {new Calcular3();}}。
初学JAVA好玩的小游戏代码

很简单的小游戏import javax.swing.JOptionPane;public class GameWithNumbers_GroupProject{public static void main(String[] args){//Create buttons for you to choose the game.Object[] options ={ "Game fight", "Find mere", "Guess numbers","Quit" };int button = JOptionPane.showOptionDialog(null, "Which action you want to do next?", "Combat Control Panel",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);if (button == JOptionPane.YES_OPTION){{Object[] options1 ={ "Attack", "Heal", "Quit" };int myap = 0 ;int enap = 0 ;int myhp = 500;int enemyhp = 500;JOptionPane.showMessageDialog(null, "This is a Fighting Game \nYou and your enemy both have 500 blood \nYou can choose attack your enemy or heal yourself next");while (myhp > 0 && enemyhp > 0){int myattack = (int)(Math.random()*100);int enemyattack = (int)(Math.random()*100);int myheal = (int)(Math.random()*50);int enemyheal = (int)(Math.random()*50);int i = JOptionPane.showOptionDialog(null, "Which action you want to do next?", "Combat Control Panel",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options1, options[0]);if (i == JOptionPane.YES_OPTION){if (myap != 100){enemyhp-=myattack;enap += 25;if(enemyhp <= 0){JOptionPane.showMessageDialog(null,"You have attacked your enemy this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + "0" + " \nGet into your enemy's turn?");break;}else{JOptionPane.showMessageDialog(null,"You have attacked your enemy this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nGet into your enemy's turn?");}}else{enemyhp-=myattack*2;enap += 25;myap = 0 ;if(enemyhp <= 0){JOptionPane.showMessageDialog(null,"You have attacked your enemy"+ " critically this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + "0" +" \nGet into your enemy's turn?");break;}else{JOptionPane.showMessageDialog(null,"You have attacked your enemy critially this "+ "turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp +" \nGet into your enemy's turn?");}}if (i == JOptionPane.NO_OPTION){myhp+=myheal;if (myhp >= 1000){myhp = 1000;}}JOptionPane.showMessageDialog(null,"You have healed yourself this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nGet into your enemy's turn?");}if (i == JOptionPane.CANCEL_OPTION){break;}int enemyif = (int)(Math.random()*2);if (enemyif == 0){if(enap !=100){myhp-=enemyattack;myap+=25;很简单的小游戏if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + myhp + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + "0" + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?"); break;}}else{myhp-=enemyattack*2;myap+=25;enap = 0;if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + myhp +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + "0" +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");break;}}}if (enemyif == 1){enemyhp+=enemyheal;if(enemyhp >= 1000){enemyhp = 1000;}JOptionPane.showMessageDialog(null,"Your enemy has healed himself this turn \nyour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nDo you want to get into your turn?");}}if (myhp <= 0){JOptionPane.showMessageDialog(null,"You die, Game Over");}if (enemyhp <= 0){JOptionPane.showMessageDialog(null,"Your enemy die, You are the winner!");}else{JOptionPane.showMessageDialog(null,"The Player Quit The Game");}}}if (button == JOptionPane.NO_OPTION){//Prompt user enter his or her birthday.int birthmonth=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the month "+ "you were born in(1 to 12):"));int birthdate=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the day "+ "you were born in:"));Constellation1(birthmonth,birthdate);}if (button == JOptionPane.CANCEL_OPTION){//Create the number and tell reader whether it is prime number:int guess=(int)(Math.random()*99+2);int guess1=(int)(Math.pow(guess,0.5));String judge="";for (int check=2; check<=guess1;check++){if(guess % check == 0)judge="The number you will guess is not a prime number";elsejudge="The number you will guess is a prime number";}JOptionPane.showMessageDialog(null,judge);//Prompt user to input the numberint user=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));do{if(user<guess)JOptionPane.showMessageDialog(null,"The number you guessed is too low, please try again!");if(user>guess)JOptionPane.showMessageDialog(null,"The number you guessed is too large, please try again!");u很简单的小游戏if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + myhp + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYourHP: " + "0" + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?"); break;}}else{myhp-=enemyattack*2;myap+=25;enap = 0;if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + myhp +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + "0" +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");break;}}}if (enemyif == 1){enemyhp+=enemyheal;if(enemyhp >= 1000){enemyhp = 1000;}JOptionPane.showMessageDialog(null,"Your enemy has healed himself this turn \nyour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nDo you want to get into your turn?");}}if (myhp <= 0){JOptionPane.showMessageDialog(null,"You die, Game Over");}if (enemyhp <= 0){JOptionPane.showMessageDialog(null,"Your enemy die, You are the winner!");}else{JOptionPane.showMessageDialog(null,"The Player Quit The Game");}}}if (button == JOptionPane.NO_OPTION){//Prompt user enter his or her birthday.int birthmonth=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the month "+ "you were born in(1 to 12):"));int birthdate=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the day "+ "you were born in:"));Constellation1(birthmonth,birthdate);}if (button == JOptionPane.CANCEL_OPTION){//Create the number and tell reader whether it is prime number:int guess=(int)(Math.random()*99+2);int guess1=(int)(Math.pow(guess,0.5));String judge="";for (int check=2; check<=guess1;check++){if(guess % check == 0)judge="The number you will guess is not a prime number";elsejudge="The number you will guess is a prime number";}JOptionPane.showMessageDialog(null,judge);//Prompt user to input the numberint user=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));do{if(user<guess)JOptionPane.showMessageDialog(null,"The number you guessed is too low, please try again!");if(user>guess)JOptionPane.showMessageDialog(null,"The number you guessed is too large, please try again!");U很简单的小游戏ser=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));}while(user != guess);JOptionPane.showMessageDialog(null,"You got the right answer!","Congratulations!",2);}}public static int Constellation1(int month, int date){if((month==3 && date>=21 && date<=31)||(month==4 && date>=1 && date<=19)) {JOptionPane.showMessageDialog(null,"You are Aries!");}else if((month==4 && date>=20 && date<=31)||(month==5 && date>=1 && date<=20)) {JOptionPane.showMessageDialog(null,"You are Taurus!");}else if((month==5 && date>=21 && date<=31)||(month==6 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Gemini!");}else if((month==6 && date>=22 && date<=30)||(month==7 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Cancer!");}else if((month==7 && date>=23 && date<=31)||(month==8 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Leo!");}else if((month==9 && date>=1 && date<=22)||(month==8 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Virgo!");}else if((month==9 && date>=23 && date<=30)||(month==10 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Libra!");}else if((month==11 && date>=1 && date<=21)||(month==10 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Scorpio!");}else if((month==11 && date>=22 && date<=30)||(month==12 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Sagittarius!");}else if((month==1 && date>=1 && date<=19)||(month==12 && date>=22 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Capricorn!");}else if((month==1 && date>=20 && date<=31)||(month==2 && date>=1 && date<=18)) {JOptionPane.showMessageDialog(null,"You are Aquarius!");}else{JOptionPane.showMessageDialog(null,"You are Pisces!");}return Constellation2(month,date);}public static int Constellation2(int month, int date){month=(int)(Math.random()*12+1);if(month==4 || month==6 || month==9 || month==11)date=(int)(Math.random()*31+1);else if(month==2)date=(int)(Math.random()*29+1);elsedate=(int)(Math.random()*30+1);String monthname="";switch(month){case 1:monthname="January";break;case 2:monthname="Feburary";break;case 3:monthname="March";break;case 4:monthname="April";break;case 5:monthname="May";break;case 6:monthname="June";break;case 7:monthname="July";break;case 8:monthname="August";break;case 9:monthname="September";break;case 10:monthname="October";break;case 11:monthname="November";break;default:monthname="December";break;}JOptionP很简单的小游戏ser=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): ")); }while(user != guess);JOptionPane.showMessageDialog(null,"You got the right answer!","Congratulations!",2);}}public static int Constellation1(int month, int date){if((month==3 && date>=21 && date<=31)||(month==4 && date>=1 && date<=19)) {JOptionPane.showMessageDialog(null,"You are Aries!");}else if((month==4 && date>=20 && date<=31)||(month==5 && date>=1 && date<=20)) {JOptionPane.showMessageDialog(null,"You are Taurus!");}else if((month==5 && date>=21 && date<=31)||(month==6 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Gemini!");}else if((month==6 && date>=22 && date<=30)||(month==7 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Cancer!");}else if((month==7 && date>=23 && date<=31)||(month==8 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Leo!");}else if((month==9 && date>=1 && date<=22)||(month==8 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Virgo!");}else if((month==9 && date>=23 && date<=30)||(month==10 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Libra!");}else if((month==11 && date>=1 && date<=21)||(month==10 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Scorpio!");}else if((month==11 && date>=22 && date<=30)||(month==12 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Sagittarius!");}else if((month==1 && date>=1 && date<=19)||(month==12 && date>=22 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Capricorn!");}else if((month==1 && date>=20 && date<=31)||(month==2 && date>=1 && date<=18)) {JOptionPane.showMessageDialog(null,"You are Aquarius!");}else{JOptionPane.showMessageDialog(null,"You are Pisces!");}return Constellation2(month,date);}public static int Constellation2(int month, int date){month=(int)(Math.random()*12+1);if(month==4 || month==6 || month==9 || month==11)date=(int)(Math.random()*31+1);else if(month==2)date=(int)(Math.random()*29+1);elsedate=(int)(Math.random()*30+1);String monthname="";switch(month){case 1:monthname="January"; break;case 2:monthname="Feburary"; break;case 3:monthname="March"; break;case 4:monthname="April"; break;case 5:monthname="May"; break;case 6:monthname="June"; break;case 7:monthname="July"; break;case 8:monthname="August"; break;case 9:monthname="September"; break;case 10:monthname="October";break;case 11:monthname="November"; break;default:monthname="December"; break;}JOptionPane.showMessageDialog(null, "You should find a fere whose birthday is "+date+ "th of "+monthname);System.exit(0);return Constellation1(month,date);}}。
java 读取文件的最后100行代码

java 读取文件的最后100行代码在 Java 中读取文件的最后 100 行代码可以通过以下步骤实现:打开文件并获取文件的总行数。
移动文件指针到倒数第 100 行的位置。
从该位置开始读取文件直到文件末尾。
下面是一个简单的 Java 代码示例来实现这个功能:import java.io.*;public class ReadLast100LinesOfFile {public static void main(String[] args) {File file = new File("your_file_path");try {RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");long fileLength = file.length();long position = fileLength - 1;int linesCount = 0;// 从文件末尾开始逐字符读取,统计行数while (position >= 0) {randomAccessFile.seek(position);int readByte = randomAccessFile.read();if (readByte == '\n') {linesCount++;if (linesCount == 100) {break;}}position--;}// 如果文件行数不足100行,则从文件头开始读取if (position < 0) {randomAccessFile.seek(0);}// 读取文件最后100行内容String line;while ((line = randomAccessFile.readLine()) != null) {System.out.println(line);}randomAccessFile.close();} catch (IOException e) {e.printStackTrace();}}}请注意替换示例代码中的"your_file_path" 为你想要读取的文件的路径。
java顺序表的基本操作代码

java顺序表的基本操作代码Java顺序表是一种基于数组实现的线性结构,具有随机访问、元素插入和删除等基本操作。
在Java中,我们可以通过定义一个数组来创建一个顺序表,并通过编写一些基本操作代码来实现对该顺序表的操作。
一、顺序表的定义和初始化在Java中,我们可以通过定义一个数组来创建一个顺序表。
下面是一个简单的代码示例:```public class SeqList<T> {private Object[] elementData; // 存储元素的数组private int size; // 当前元素个数// 构造函数public SeqList(int capacity) {elementData = new Object[capacity];size = 0;}}```在上述代码中,我们定义了一个SeqList类,其中包含了存储元素的数组elementData和当前元素个数size两个成员变量。
构造函数SeqList(int capacity)用于创建指定长度为capacity的数组,并将当前元素个数初始化为0。
二、顺序表的插入操作1. 在指定位置插入元素在Java中,我们可以通过下标来访问数组中的元素。
因此,在进行插入操作时,需要先将要插入位置之后的所有元素向后移动一位,然后再将新元素插入到指定位置上。
下面是一个简单的代码示例:```// 在指定位置插入元素public void insert(int index, T element) {if (index < 0 || index > size) {throw new IndexOutOfBoundsException("插入位置越界"); }// 判断数组是否已满,若已满则扩容if (size == elementData.length) {ensureCapacity(size * 2);}// 将要插入位置之后的所有元素向后移动一位for (int i = size - 1; i >= index; i--) {elementData[i + 1] = elementData[i];}// 插入新元素elementData[index] = element;size++;}// 扩容方法private void ensureCapacity(int minCapacity) {if (minCapacity > elementData.length) {Object[] newArray = new Object[minCapacity];System.arraycopy(elementData, 0, newArray, 0, size);elementData = newArray;}}```在上述代码中,我们首先判断要插入的位置是否越界。
mqttserverjava_MQTT推送简单例子服务端java代码实现

mqttserverjava_MQTT推送简单例子服务端java代码实现下面是一个简单的MQTT服务端的Java实现代码:```javaimport org.eclipse.paho.client.mqttv3.*;importorg.eclipse.paho.client.mqttv3.persist.MemoryPersistence;public class MqttServerpublic static void main(String[] args)String broker = "tcp://localhost:1883";String topic = "test";int qos = 2;tryMqttServerPersistence persistence = new MemoryPersistence(;MqttServerClient mqttClient = new MqttClient(broker, MqttServerClient.generateClientId(, persistence);mqttClient.setCallback(new MqttCallbacpublic void connectionLost(Throwable throwable) {}public void messageArrived(String s, MqttMessage mqttMessage) throws ExceptionSystem.out.println("Received message: " + newString(mqttMessage.getPayload());}});mqttClient.connect(;mqttClient.subscribe(topic, qos);System.out.println("MQTT Server is running...");// Keep the server runningwhile(true)}} catch (MqttException e)e.printStackTrace(;}}```上述代码使用了Eclipse Paho MQTT客户端库来实现MQTT服务端。
java快速排序简单代码

java快速排序简单代码快速排序是一种非常高效的排序算法,它利用了分治的思想,可以在O(n log n)的时间复杂度内完成排序,比其他排序算法的速度要快得多。
在Java中,快速排序的实现并不复杂,下面就来详细介绍。
1. 选取基准点快速排序的第一步是选取基准点,在我们的代码中,我们选取数组的第一个元素为基准点,可以根据需要进行修改。
2. 分区接下来,我们需要将数组中的元素按照基准点进行分区,将比基准点小的元素放置到基准点的左边,比基准点大的元素放置到基准点的右边。
我们可以用两个指针 i 和 j 分别从左边和右边扫描数组,比较大小并交换元素,直到 i >= j。
3. 递归排序分区完成后,我们需要对左右两个分区再次进行快速排序。
我们可以使用递归的方式来实现这一过程,对左分区和右分区分别调用快速排序函数,直到所有分区都变得有序。
下面是快速排序的Java实现代码:public static void quickSort(int[] arr, int left, int right) {if (left >= right) {return;}int pivot = arr[left];int i = left, j = right;while (i < j) {while (i < j && arr[j] >= pivot) {j--;}arr[i] = arr[j];while (i < j && arr[i] <= pivot) {i++;}arr[j] = arr[i];}arr[i] = pivot;quickSort(arr, left, i - 1);quickSort(arr, i + 1, right);}在代码中,我们首先判断了左右指针是否相遇,防止出现越界的情况。
接着,我们选取了左边第一个元素作为基准点,并使用指针 i 和 j 进行分区操作,最后对左右两个分区进行递归排序。
java编程100例
}
//for循环操作
for(int i=0;i<iEnd;i++)
{
System.out.println("这是for 第"+i+"次循环");
}
//while循环操作
}
}
[JAVA100例]004、矢量(Vector)对象的操作
public class operateVector
{
/*
*<br>方法说明:生成一个4*4的二维Vector,供使用。
*<br>输入参数:
*<br>输出变量:Vector
*<br>其它说明:
*/
public Vector buildVector(){
//演示是否是英文字符
boolean bIsStr = mA.isString("wer");
System.out.println("1:bIsStr="+bIsStr);
bIsStr = mA.isString("wer3");
System.out.println("2:bIsStr="+bIsStr);
for(int j=0;j<cStr.length;j++){
if(cTemp==cStr[j]){
bTemp = true;
break;
}
}
if(!bTemp) return false;
}
return 0;
java先进后出栈的代码
java先进后出栈的代码在Java 中,可以使用`Stack` 类来实现先进后出(LIFO)的栈数据结构。
以下是一个简单的示例代码:```javaimport java.util.Stack;public class StackExample {public static void main(String[] args) {// 创建一个栈Stack<String> stack = new Stack<>();// 压栈(入栈)stack.push("Element 1");stack.push("Element 2");stack.push("Element 3");// 出栈while (!stack.isEmpty()) {String element = stack.pop();System.out.println("出栈: " + element);}}}```在这个例子中,我们使用`Stack<String>` 来创建一个字符串类型的栈。
通过`push` 方法将元素压入栈,通过`pop` 方法将元素从栈顶弹出。
使用`isEmpty` 方法检查栈是否为空。
注意:`Stack` 类在Java 中是线程安全的,但它被标记为过时(deprecated)。
在实际应用中,更推荐使用`Deque` 的实现类`LinkedList` 作为栈,因为`LinkedList` 实现了`Deque` 接口,同时具有栈和队列的特性。
```javaimport java.util.LinkedList;import java.util.Deque;public class StackExample {public static void main(String[] args) {// 创建一个栈Deque<String> stack = new LinkedList<>();// 压栈(入栈)stack.push("Element 1");stack.push("Element 2");stack.push("Element 3");// 出栈while (!stack.isEmpty()) {String element = stack.pop();System.out.println("出栈: " + element);}}}```这个例子中,我们使用`LinkedList` 来实现栈的功能。
java发光圣诞树的代码编写
java发光圣诞树的代码编写在Java中编写一个发光的圣诞树可以是一项有趣的挑战。
以下是一个简单的示例代码,可以帮助你创建一个发光的圣诞树:import java.awt.Color;import java.awt.Graphics;import javax.swing.JFrame;import javax.swing.JPanel;public class GlowingChristmasTree extends JPanel {public void paint(Graphics g) {// 设置绘制区域的背景颜色为黑色setBackground(Color.BLACK);// 绘制圣诞树的主干g.setColor(Color.GREEN);g.fillRect(300, 250, 20, 150);// 绘制圣诞树的叶子// 第一层g.setColor(Color.GREEN);g.fillOval(250, 200, 120, 120);// 第二层g.setColor(Color.RED);g.fillOval(225, 160, 170, 170); // 第三层g.setColor(Color.GREEN);g.fillOval(200, 120, 220, 220); // 第四层g.setColor(Color.RED);g.fillOval(175, 80, 270, 270); // 第五层g.setColor(Color.GREEN);g.fillOval(150, 40, 320, 320);// 绘制圣诞树的彩灯g.setColor(Color.YELLOW);g.fillOval(280, 200, 20, 20);g.fillOval(310, 180, 20, 20);g.fillOval(340, 200, 20, 20);g.fillOval(360, 230, 20, 20);g.fillOval(350, 260, 20, 20);g.fillOval(330, 290, 20, 20);g.fillOval(300, 310, 20, 20); g.fillOval(270, 290, 20, 20);g.fillOval(250, 260, 20, 20);g.fillOval(245, 230, 20, 20);}public static void main(String[] args) {// 创建一个新的 JFrameJFrame frame = new JFrame();// 将绘制区域添加到 JFrame 中frame.add(new GlowingChristmasTree());// 设置 JFrame 的大小和标题frame.setSize(650, 500);frame.setTitle('Glowing Christmas Tree');// 设置 JFrame 关闭时的操作frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 让 JFrame 可见frame.setVisible(true);}}在该代码中,我们使用Java的绘图API来绘制圣诞树和彩灯。
java常用代码(20条案例)
java常用代码(20条案例)1. 输出Hello World字符串public class Main {public static void main(String[] args) {// 使用System.out.println()方法输出字符串"Hello World"System.out.println("Hello World");}}2. 定义一个整型变量并进行赋值public class Main {public static void main(String[] args) {// 定义一个名为num的整型变量并将其赋值为10int num = 10;// 使用System.out.println()方法输出变量num的值System.out.println(num);}}3. 循环打印数字1到10public class Main {public static void main(String[] args) {// 使用for循环遍历数字1到10for (int i = 1; i <= 10; i++) {// 使用System.out.println()方法输出每个数字System.out.println(i);}}}4. 实现输入输出import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);// 使用scanner.nextLine()方法获取用户输入的字符串String input = scanner.nextLine();// 使用System.out.println()方法输出输入的内容System.out.println("输入的是:" + input);}}5. 实现条件分支public class Main {public static void main(String[] args) {// 定义一个整型变量num并将其赋值为10int num = 10;// 使用if语句判断num是否大于0,如果是,则输出"这个数是正数",否则输出"这个数是负数"if (num > 0) {System.out.println("这个数是正数");} else {System.out.println("这个数是负数");}}}6. 使用数组存储数据public class Main {public static void main(String[] args) {// 定义一个整型数组nums,其中包含数字1到5int[] nums = new int[]{1, 2, 3, 4, 5};// 使用for循环遍历数组for (int i = 0; i < nums.length; i++) {// 使用System.out.println()方法输出每个数组元素的值System.out.println(nums[i]);}}}7. 打印字符串长度public class Main {public static void main(String[] args) {// 定义一个字符串变量str并将其赋值为"HelloWorld"String str = "Hello World";// 使用str.length()方法获取字符串的长度,并使用System.out.println()方法输出长度System.out.println(str.length());}}8. 字符串拼接public class Main {public static void main(String[] args) {// 定义两个字符串变量str1和str2,并分别赋值为"Hello"和"World"String str1 = "Hello";String str2 = "World";// 使用"+"号将两个字符串拼接成一个新字符串,并使用System.out.println()方法输出拼接后的结果System.out.println(str1 + " " + str2);}}9. 使用方法进行多次调用public class Main {public static void main(String[] args) {// 定义一个名为str的字符串变量并将其赋值为"Hello World"String str = "Hello World";// 调用printStr()方法,打印字符串变量str的值printStr(str);// 调用add()方法,计算两个整数的和并输出结果int result = add(1, 2);System.out.println(result);}// 定义一个静态方法printStr,用于打印字符串public static void printStr(String str) {System.out.println(str);}// 定义一个静态方法add,用于计算两个整数的和public static int add(int a, int b) {return a + b;}}10. 使用继承实现多态public class Main {public static void main(String[] args) {// 创建一个Animal对象animal,并调用move()方法Animal animal = new Animal();animal.move();// 创建一个Dog对象dog,并调用move()方法Dog dog = new Dog();dog.move();// 创建一个Animal对象animal2,但其实际指向一个Dog对象,同样调用move()方法Animal animal2 = new Dog();animal2.move();}}// 定义一个Animal类class Animal {public void move() {System.out.println("动物在移动");}}// 定义一个Dog类,继承自Animal,并重写了move()方法class Dog extends Animal {public void move() {System.out.println("狗在奔跑");}}11. 输入多个数并求和import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);// 定义一个整型变量sum并将其赋值为0int sum = 0;// 使用while循环持续获取用户输入的整数并计算总和,直到用户输入为0时结束循环while (true) {System.out.println("请输入一个整数(输入0退出):");int num = scanner.nextInt();if (num == 0) {break;}sum += num;}// 使用System.out.println()方法输出总和System.out.println("所有输入的数的和为:" + sum);}}12. 判断一个年份是否为闰年import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);// 使用scanner.nextInt()方法获取用户输入的年份System.out.println("请输入一个年份:");int year = scanner.nextInt();// 使用if语句判断年份是否为闰年,如果是,则输出"是闰年",否则输出"不是闰年"if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {System.out.println(year + "年是闰年");} else {System.out.println(year + "年不是闰年");}}}13. 使用递归实现斐波那契数列import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);// 使用scanner.nextInt()方法获取用户输入的正整数nSystem.out.println("请输入一个正整数:");int n = scanner.nextInt();// 使用for循环遍历斐波那契数列for (int i = 1; i <= n; i++) {System.out.print(fibonacci(i) + " ");}}// 定义一个静态方法fibonacci,使用递归计算斐波那契数列的第n项public static int fibonacci(int n) {if (n <= 2) {return 1;} else {return fibonacci(n - 1) + fibonacci(n - 2);}}}14. 输出九九乘法表public class Main {public static void main(String[] args) {// 使用两层for循环打印九九乘法表for (int i = 1; i <= 9; i++) {for (int j = 1; j <= i; j++) {System.out.print(j + "*" + i + "=" + (i * j) + "\t");}System.out.println();}}}15. 使用try-catch-finally处理异常import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);try {// 使用scanner.nextInt()方法获取用户输入的整数a和bSystem.out.println("请输入两个整数:");int a = scanner.nextInt();int b = scanner.nextInt();// 对a进行除以b的运算int result = a / b;// 使用System.out.println()方法输出结果System.out.println("计算结果为:" + result);} catch (ArithmeticException e) {// 如果除数为0,会抛出ArithmeticException异常,捕获异常并使用System.out.println()方法输出提示信息System.out.println("除数不能为0");} finally {// 使用System.out.println()方法输出提示信息System.out.println("程序结束");}}}16. 使用集合存储数据并遍历import java.util.ArrayList;import java.util.List;public class Main {public static void main(String[] args) {// 创建一个名为list的List集合,并添加多个字符串元素List<String> list = new ArrayList<>();list.add("Java");list.add("Python");list.add("C++");list.add("JavaScript");// 使用for循环遍历List集合并使用System.out.println()方法输出每个元素的值for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));}}}17. 使用Map存储数据并遍历import java.util.HashMap;import java.util.Map;public class Main {public static void main(String[] args) {// 创建一个名为map的Map对象,并添加多组键值对Map<Integer, String> map = new HashMap<>();map.put(1, "Java");map.put(2, "Python");map.put(3, "C++");map.put(4, "JavaScript");// 使用for-each循环遍历Map对象并使用System.out.println()方法输出每个键值对的值for (Map.Entry<Integer, String> entry :map.entrySet()) {System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());}}}18. 使用lambda表达式进行排序import java.util.ArrayList;import java.util.Collections;import parator;import java.util.List;public class Main {public static void main(String[] args) {// 创建一个名为list的List集合,并添加多个字符串元素List<String> list = new ArrayList<>();list.add("Java");list.add("Python");list.add("C++");list.add("JavaScript");// 使用lambda表达式定义Comparator接口的compare()方法,按照字符串长度进行排序Comparator<String> stringLengthComparator = (s1, s2) -> s1.length() - s2.length();// 使用Collections.sort()方法将List集合进行排序Collections.sort(list, stringLengthComparator);// 使用for-each循环遍历List集合并使用System.out.println()方法输出每个元素的值for (String str : list) {System.out.println(str);}}}19. 使用线程池执行任务import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Main {public static void main(String[] args) {// 创建一个名为executor的线程池对象,其中包含2个线程ExecutorService executor =Executors.newFixedThreadPool(2);// 使用executor.execute()方法将多个Runnable任务加入线程池中进行执行executor.execute(new MyTask("任务1"));executor.execute(new MyTask("任务2"));executor.execute(new MyTask("任务3"));// 调用executor.shutdown()方法关闭线程池executor.shutdown();}}// 定义一个MyTask类,实现Runnable接口,用于代表一个任务class MyTask implements Runnable {private String name;public MyTask(String name) { = name;}@Overridepublic void run() {System.out.println("线程" +Thread.currentThread().getName() + "正在执行任务:" + name);try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("线程" +Thread.currentThread().getName() + "完成任务:" + name);}}20. 使用JavaFX创建图形用户界面import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import yout.StackPane;import javafx.stage.Stage;public class Main extends Application {@Overridepublic void start(Stage primaryStage) throws Exception { // 创建一个Button对象btn,并设置按钮名称Button btn = new Button("点击我");// 创建一个StackPane对象pane,并将btn添加到pane中StackPane pane = new StackPane();pane.getChildren().add(btn);// 创建一个Scene对象scene,并将pane作为参数传入Scene scene = new Scene(pane, 200, 100);// 将scene设置为primaryStage的场景primaryStage.setScene(scene);// 将primaryStage的标题设置为"JavaFX窗口"primaryStage.setTitle("JavaFX窗口");// 调用primaryStage.show()方法显示窗口primaryStage.show();}public static void main(String[] args) { launch(args);}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
简单的java代码
简单的java代码
Java是一种面向对象的编程语言,它具有简单、可移植、安全和高性能等特点。
在Java中,我们可以编写各种各样的代码,从简单的“Hello World”程序到复杂的企业级应用程序都可以使用Java来实现。
在本文中,我们将介绍一些简单的Java代码示例。
一、Hello World程序
“Hello World”程序是任何编程语言中最基本和最常见的程序之一。
在Java中,我们可以使用以下代码来实现:
```
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```
这个程序很简单,它定义了一个名为“HelloWorld”的类,并在其中定义了一个名为“main”的方法。
该方法通过调用
System.out.println()方法来输出“Hello, World!”字符串。
二、计算两个数之和
下面是一个简单的Java程序,用于计算两个数之和:
```
import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
int num1, num2, sum;
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter second number: ");
num2 = input.nextInt();
sum = num1 + num2;
System.out.println("Sum of the two numbers is " + sum); }
}
该程序首先导入了java.util.Scanner类,以便从控制台读取输入。
然后,它定义了三个变量:num1,num2和sum。
接下来,程序提示
用户输入两个数字,并使用Scanner类从控制台读取这些数字。
最后,程序计算这两个数字的总和,并将结果输出到控制台。
三、计算圆的面积
下面是一个简单的Java程序,用于计算圆的面积:
```
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
double radius, area;
Scanner input = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
radius = input.nextDouble();
area = Math.PI * radius * radius;
System.out.println("The area of the circle is " + area);
}
```
该程序首先导入了java.util.Scanner类,以便从控制台读取输入。
然后,它定义了两个变量:radius和area。
接下来,程序提示用户输入圆的半径,并使用Scanner类从控制台读取这个值。
最后,程序使用Math.PI常量和半径计算圆的面积,并将结果输出到控制台。
四、判断一个数是否为偶数
下面是一个简单的Java程序,用于判断一个数是否为偶数:
```
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}
}
}
```
该程序首先导入了java.util.Scanner类,以便从控制台读取输入。
然后,它定义了一个变量num。
接下来,程序提示用户输入一个数字,并使用Scanner类从控制台读取这个值。
最后,程序使用if-else语句来判断这个数字是否为偶数,并将结果输出到控制台。
五、计算阶乘
下面是一个简单的Java程序,用于计算一个数的阶乘:
```
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
int num, fact = 1;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial of " + num + " is " + fact);
}
}
```
该程序首先导入了java.util.Scanner类,以便从控制台读取输入。
然后,它定义了两个变量:num和fact。
接下来,程序提示用户输入一个数字,并使用Scanner类从控制台读取这个值。
最后,程序使用for循环来计算这个数字的阶乘,并将结果输出到控制台。
总结
以上是一些简单的Java代码示例。
Java是一种非常强大和灵活的编程语言,可以用于开发各种各样的应用程序。
如果您想深入了解Java编程,建议您学习Java的基础知识,并尝试编写一些简单的程序。