您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了java如何使用JOptionPane實現猜數字游戲,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
一、我猜數字
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如何使用JOptionPane實現猜數字游戲的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。