您好,登錄后才能下訂單哦!
這篇文章主要介紹Java中怎么實現帶GUI界面的猜數字游戲,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
先導包
import java.util.*; import javax.swing.*;
再寫主方法
public static void main(String[] args) { }
新聲明一個Scanner和隨機數
public static void main(String[] args) { Scanner in = new Scanner(System.in); Random r = new Random(); }
讓UIManager爬取系統窗口樣式
try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); }
新建一個int類型的變量存儲隨機數
int secret = r.nextInt(32) + 1;
寫入主程序
JOptionPane.showMessageDialog(null, "電腦隨機生成了一個1~32之間的數,請猜出這個數", "猜數字游戲", JOptionPane.PLAIN_MESSAGE); String number2 = (String) JOptionPane.showInputDialog(null, "請輸入想猜的數:", "猜數字游戲", JOptionPane.PLAIN_MESSAGE, null, null, ""); int number = Integer.parseInt(number2); while (number != secret) { if (number > secret) { JOptionPane.showMessageDialog(null, "你猜的數大了,請繼續猜", "猜數字游戲", JOptionPane.PLAIN_MESSAGE); number2 = (String) JOptionPane.showInputDialog(null, "請輸入想猜的數:", "猜數字游戲", JOptionPane.PLAIN_MESSAGE, null, null, ""); number = Integer.parseInt(number2); } else { JOptionPane.showMessageDialog(null, "你猜的數小了,請繼續猜", "猜數字游戲", JOptionPane.PLAIN_MESSAGE); number2 = (String) JOptionPane.showInputDialog(null, "請輸入想猜的數:", "猜數字游戲", JOptionPane.PLAIN_MESSAGE, null, null, ""); number = Integer.parseInt(number2); } } JOptionPane.showMessageDialog(null, "恭喜你,你猜對了,電腦生成的隨機數是" + secret, "猜數字游戲", JOptionPane.PLAIN_MESSAGE);
全部代碼
package com.demo05; import java.util.*; import javax.swing.*; public class MathDemo03 { public static void main(String[] args) { Scanner in = new Scanner(System.in); Random r = new Random(); int secret = r.nextInt(32) + 1; try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "電腦隨機生成了一個1~32之間的數,請猜出這個數", "猜數字游戲", JOptionPane.PLAIN_MESSAGE); String number2 = (String) JOptionPane.showInputDialog(null, "請輸入想猜的數:", "猜數字游戲", JOptionPane.PLAIN_MESSAGE, null, null, ""); int number = Integer.parseInt(number2); while (number != secret) { if (number > secret) { JOptionPane.showMessageDialog(null, "你猜的數大了,請繼續猜", "猜數字游戲", JOptionPane.PLAIN_MESSAGE); number2 = (String) JOptionPane.showInputDialog(null, "請輸入想猜的數:", "猜數字游戲", JOptionPane.PLAIN_MESSAGE, null, null, ""); number = Integer.parseInt(number2); } else { JOptionPane.showMessageDialog(null, "你猜的數小了,請繼續猜", "猜數字游戲", JOptionPane.PLAIN_MESSAGE); number2 = (String) JOptionPane.showInputDialog(null, "請輸入想猜的數:", "猜數字游戲", JOptionPane.PLAIN_MESSAGE, null, null, ""); number = Integer.parseInt(number2); } } JOptionPane.showMessageDialog(null, "恭喜你,你猜對了,電腦生成的隨機數是" + secret, "猜數字游戲", JOptionPane.PLAIN_MESSAGE); } }
以上是“Java中怎么實現帶GUI界面的猜數字游戲”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。