- package bn.tw;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- // TODO 自動產生的方法 Stub
- int ans = (int) (Math.random() * 99 + 1);
- System.out.println("猜1~99的數字:");
- int small = 1;
- int big = 99;
- int total = 1;
- int guess = 0;
- while (true) {
- try {
- Scanner scanner = new Scanner(System.in);
- guess = scanner.nextInt();
- } catch (Exception e) {
- System.out.println("重新輸入");
- guess = 1;
- total--;
- }
- if (guess > ans) {
- System.out.println("太大");
- System.out.println(small + "~" + guess);
- big = guess;
- total++;
- } else if (guess < ans) {
- System.out.println("太小");
- System.out.println(guess + "~" + big);
- small = guess;
- total++;
- } else {
- System.out.println("GOTCHA!");
- System.out.println("一共猜了" + total + "次");
- break;
- }
- }
- }
- }
複製代碼 |