Time in the Subway: 猜數字小遊戲(GuessNum)--Java程式碼實現
阿新 • • 發佈:2018-12-22
/*
需求:開發一個猜數字的小遊戲;
* 描述:系統產生一個1-100之間的隨機數(含0和100),請猜出這個數字是多少。
* 1.產生隨機數
* 2.接收鍵盤輸入數字
* 3.判斷大小,輸出結果。
* 4.使用者一局最多7次猜的機會,猜不中則遊戲結束。
* 4.每局遊戲結束後要能給出使用者選擇:再來一局還是結束遊戲。
*/
import java.util.Random;
import java.util.Scanner;
public class GuessNumOptimize {
Scanner sc = new Scanner(System.in );
static int times = 6;
public static void main(String[] args) {
System.out.println("Hello, MZ. WLCOME HERE! ^_^ ");
System.out.println("This is a game which invites you to guess a number between 1 and 100,include 1 and 100.");
System.out.println("And you have at most " + times + " times to try in each inning.");
System.out.print("Press 1 to Start. ");
System.out.println("Press 2 to Quit. : ");
Scanner sc = new Scanner(System.in);
flag: while (true) {
System.out.println("Please enter your choice :");
int button = sc.nextInt();
switch (button) {
case 1:
System.out.println("Start Now!");
Random r = new Random();
int answer = r.nextInt(100) + 1;
// 產生隨機數,判斷答案,一局結束。
judgeNum(answer);
break;
case 2:
System.out.println("Game Over!");
System.out.println("歡迎下次再來!");
break flag;
// System.exit(0);
default:
System.out.println("Are u kidding?");
System.out.print("Press 1 to try again. ");
System.out.println("Press 2 to Quit. : ");
break;
}
}
}
// 定義判斷方法:judgeNum(int answer)
public static void judgeNum(int answer) {
for (int i = times; i >= 1; i--) {
System.out.println("------------------------");
System.out.println("Please enter your number:");
Scanner sc = new Scanner(System.in);
int enterNum = sc.nextInt();
// 判斷大小
if (enterNum > answer) {
if (i == 1) {
System.out.println("很遺憾,你沒有機會了!");
endPrompt();
break;
} else {
System.out.println("你猜大了,往小了猜試試?");
System.out.println("你還有" + (i - 1) + "次機會。加油!");
}
} else if (enterNum < answer) {
if (i == 1 ) {
System.out.println("很遺憾,你沒有機會了!");
endPrompt();
break;
} else {
System.out.println("你猜小了,往大了猜試試?");
System.out.println("你還有" + (i - 1) + "次機會。加油!");
}
} else {
System.out.println("恭喜你,猜中啦。答案是:" + enterNum + "。");
System.out.println("你用了" + (times - i +1) + "次就猜對了,好厲害!*^_^* ");
endPrompt();
break;
}
}
}
//每局結束的提示語
public static void endPrompt(){
System.out.println("再來一局?");
System.out.println("Press 1 to Try Again.");
System.out.println("Press 2 to Quit.");
}