java使用JOptionPane猜数字游戏
时间: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; } }
更多有趣的经典小游戏实现专题,也分享给大家:
上一篇:Java爬虫抓取视频网站下载链接
栏 目:JAVA代码
下一篇:java遍历http请求request的所有参数实现方法
本文地址:http://www.codeinn.net/misctech/33622.html
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机