时间:2020-12-17 01:54:03 | 栏目:JAVA代码 | 点击:次
本文实例为大家分享了java实现猜数字游戏的具体代码,供大家参考,具体内容如下
一、我猜数字
import java.util.Random; import javax.swing.JOptionPane; public class MyRandom { public static void main(String[] args) { //生成随机数 Random randomNumber = new Random(); int myNum = randomNumber.nextInt(10); String guessNum = ""; int guessNumber = 0; //猜对猜错的标识 boolean sign = false; //猜数字的循环 do{ try{ guessNum = JOptionPane.showInputDialog(null,"欢迎来到猜数字游戏!,请输入数字"); guessNumber = Integer.parseInt(guessNum); if(guessNumber > myNum) { JOptionPane.showMessageDialog(null,"猜大了"); } else if(guessNumber < myNum) { JOptionPane.showMessageDialog(null,"猜小了"); } else { sign = true; } }catch(NumberFormatException e){ JOptionPane.showMessageDialog(null,"输入格式错误"); } }while(guessNumber != myNum); if(sign) { JOptionPane.showMessageDialog(null,"恭喜你猜对了!"); } } }
二、电脑猜数字
import javax.swing.JOptionPane; import java.util.ArrayList; import java.util.Random; public class ComRandom { //给猜的数设置一个范围 int low = 0, high = 10; boolean leave = false; public void run() { int myIntNumber = 0; String myNumber; try{ //给电脑一个数让他猜 myNumber = JOptionPane.showInputDialog(null,"给我一个0-10的数字,让我(电脑)来猜"); try{ myIntNumber = Integer.parseInt(myNumber); }catch(NumberFormatException e){ JOptionPane.showMessageDialog(null,"异常"); leave = true; } }catch(NullPointerException e){ JOptionPane.showMessageDialog(null,"拜拜"); } if(!leave){ //电脑随机猜一次,生成一个随机的数字 Random randomGenerator= new Random(); int guessNumber = randomGenerator.nextInt(10); //循环判断电脑猜的数字是大还是小 //定义两个字符串,提示电脑是猜大了还是猜小了。 String output = ""; try{ output = JOptionPane.showInputDialog(null,"是" + guessNumber + "!我猜对了吗?"); while(!output.equals("猜对了")) { if(output.equals("猜大了")) { guessNumber = guessNumber(guessNumber,myIntNumber); } else if(output.equals("猜小了")) { guessNumber = guessNumber(guessNumber, myIntNumber); } else { JOptionPane.showMessageDialog(null,"我没听懂你在说什么..."); } try{ output = JOptionPane.showInputDialog(null,"是" + guessNumber + "!我猜对了吗?"); }catch(NullPointerException e) { JOptionPane.showMessageDialog(null,"异常"); } } }catch(NullPointerException e){ JOptionPane.showMessageDialog(null,"异常"); } } leave = false; } /** * 二分法猜数字 */ private int guessNumber(int guess,int number) { if(guess < number) { //答案是5 我猜的是2 low = guess + 1; } else if(guess > number) { //答案是6我猜的是8 high = guess - 1; } guess = (high + low) / 2; return guess; } }
更多有趣的经典小游戏实现专题,也分享给大家: