1. 程式人生 > 程式設計 >Java的帶GUI介面猜數字遊戲的實現示例

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,"");
int number = Integer.parseInt(number2);
while (number != secret) {
  if (number > secret) {
    JOptionPane.showMessageDialog(null,"你猜的數大了,請繼續猜",JOptionPane.PLAIN_MESSAGE);
    number2 = (String) JOptionPane.showInputDialog(null,"");
    number = Integer.parseInt(number2);
  } else {
    JOptionPane.showMessageDialog(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,JOptionPane.PLAIN_MESSAGE);
    String number2 = (String) JOptionPane.showInputDialog(null,"");
    int number = Integer.parseInt(number2);
    while (number != secret) {
      if (number > secret) {
        JOptionPane.showMessageDialog(null,JOptionPane.PLAIN_MESSAGE);
        number2 = (String) JOptionPane.showInputDialog(null,"");
        number = Integer.parseInt(number2);
      } else {
        JOptionPane.showMessageDialog(null,"");
        number = Integer.parseInt(number2);
      }
    }
    JOptionPane.showMessageDialog(null,JOptionPane.PLAIN_MESSAGE);
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。