java使用JOptionPane猜數字游戲
本文實例為大家分享了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經典小游戲匯總
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: