本文實(shí)例講述了java實(shí)現(xiàn)的簡單猜數(shù)字游戲代碼。分享給大家供大家參考。
具體代碼如下:
public class Main {
public static void main(String[] args) {
// 產(chǎn)生一個(gè)隨機(jī)數(shù)
int number = (int) (Math.random() * 100) + 1;
// 加入count
int count = 0;
// 在這里加入最大值,和最小值
int max = 100;
int min = 1;
while (true) {
// 鍵盤錄入數(shù)據(jù)
Scanner sc = new Scanner(System.in);
System.out.println("請輸入你要猜的數(shù)據(jù):(" + min + "~" + max + ")");
try {
count++;
int guessNumber = sc.nextInt();
// 判斷
if (guessNumber > number) {
max = guessNumber;
System.out.println("你猜大了");
} else if (guessNumber < number) {
min = guessNumber;
System.out.println("你猜小了");
} else {
System.out.println("恭喜你,花了" + count + "次就猜中了");
// 問是否繼續(xù)
System.out.println("請問還要繼續(xù)嗎?(yes)");
sc = new Scanner(System.in);
String str = sc.nextLine();
if ("yes".equals(str)) {
// 重寫賦值隨機(jī)數(shù)
number = (int) (Math.random() * 100) + 1;
count = 0;
max = 100;
min = 1;
} else {
break;
}
}
} catch (InputMismatchException e) {
System.out.println("你輸入的數(shù)據(jù)有誤");
}
}
}
}
運(yùn)行結(jié)果如下圖所示:
希望本文所述對(duì)大家的java程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選