import java.util.Random;
import java.util.Scanner;
publicclass GuessNumOptimize {
Scanner sc = new Scanner(System.in);
staticint times = 6;
publicstaticvoidmain(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) {
case1:
System.out.println("Start Now!");
Random r = new Random();
int answer = r.nextInt(100) + 1;
// 产生随机数,判断答案,一局结束。
judgeNum(answer);
break;
case2:
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)publicstaticvoidjudgeNum(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) + "次机会。加油!");
}
} elseif (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;
}
}
}
//每局结束的提示语publicstaticvoidendPrompt(){
System.out.println("再来一局?");
System.out.println("Press 1 to Try Again.");
System.out.println("Press 2 to Quit.");
}