您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了java如何使用JOptionPane實(shí)現(xiàn)猜數(shù)字游戲,內(nèi)容簡而易懂,希望大家可以學(xué)習(xí)一下,學(xué)習(xí)完之后肯定會(huì)有收獲的,下面讓小編帶大家一起來看看吧。
一、我猜數(shù)字
import java.util.Random; import javax.swing.JOptionPane; public class MyRandom { public static void main(String[] args) { //生成隨機(jī)數(shù) Random randomNumber = new Random(); int myNum = randomNumber.nextInt(10); String guessNum = ""; int guessNumber = 0; //猜對(duì)猜錯(cuò)的標(biāo)識(shí) boolean sign = false; //猜數(shù)字的循環(huán) do{ try{ guessNum = JOptionPane.showInputDialog(null,"歡迎來到猜數(shù)字游戲!,請(qǐng)輸入數(shù)字"); 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,"輸入格式錯(cuò)誤"); } }while(guessNumber != myNum); if(sign) { JOptionPane.showMessageDialog(null,"恭喜你猜對(duì)了!"); } } }
二、電腦猜數(shù)字
import javax.swing.JOptionPane; import java.util.ArrayList; import java.util.Random; public class ComRandom { //給猜的數(shù)設(shè)置一個(gè)范圍 int low = 0, high = 10; boolean leave = false; public void run() { int myIntNumber = 0; String myNumber; try{ //給電腦一個(gè)數(shù)讓他猜 myNumber = JOptionPane.showInputDialog(null,"給我一個(gè)0-10的數(shù)字,讓我(電腦)來猜"); try{ myIntNumber = Integer.parseInt(myNumber); }catch(NumberFormatException e){ JOptionPane.showMessageDialog(null,"異常"); leave = true; } }catch(NullPointerException e){ JOptionPane.showMessageDialog(null,"拜拜"); } if(!leave){ //電腦隨機(jī)猜一次,生成一個(gè)隨機(jī)的數(shù)字 Random randomGenerator= new Random(); int guessNumber = randomGenerator.nextInt(10); //循環(huán)判斷電腦猜的數(shù)字是大還是小 //定義兩個(gè)字符串,提示電腦是猜大了還是猜小了。 String output = ""; try{ output = JOptionPane.showInputDialog(null,"是" + guessNumber + "!我猜對(duì)了嗎?"); while(!output.equals("猜對(duì)了")) { 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 + "!我猜對(duì)了嗎?"); }catch(NullPointerException e) { JOptionPane.showMessageDialog(null,"異常"); } } }catch(NullPointerException e){ JOptionPane.showMessageDialog(null,"異常"); } } leave = false; } /** * 二分法猜數(shù)字 */ 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; } }
以上就是關(guān)于java如何使用JOptionPane實(shí)現(xiàn)猜數(shù)字游戲的內(nèi)容,如果你們有學(xué)習(xí)到知識(shí)或者技能,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。