当前位置 : 主页 > 编程语言 > java >

java使用JOptionPane猜数字游戏

来源:互联网 收集:自由互联 发布时间:2021-04-30
本文实例为大家分享了java实现猜数字游戏的具体代码,供大家参考,具体内容如下 一、我猜数字 import java.util.Random;import javax.swing.JOptionPane;public class MyRandom{ public static void main(String[]

本文实例为大家分享了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;
 }
}

更多有趣的经典小游戏实现专题,也分享给大家:

C++经典小游戏汇总

python经典小游戏汇总

python俄罗斯方块游戏集合

JavaScript经典游戏 玩不停

java经典小游戏汇总

javascript经典小游戏汇总

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

网友评论