返回列表 發帖
  1. package bn.tw;

  2. import java.util.Scanner;

  3. public class Main {

  4.         public static void main(String[] args) {
  5.                 // TODO 自動產生的方法 Stub
  6.                 int ans = (int) (Math.random() * 99 + 1);
  7.                 System.out.println("猜1~99的數字:");
  8.                 int small = 1;
  9.                 int big = 99;
  10.                 int total = 1;
  11.                 int guess = 0;
  12.                 while (true) {
  13.                         try {
  14.                                 Scanner scanner = new Scanner(System.in);
  15.                                 guess = scanner.nextInt();
  16.                         } catch (Exception e) {
  17.                                 System.out.println("重新輸入");
  18.                                 guess = 1;
  19.                                 total--;
  20.                         }

  21.                         if (guess > ans) {
  22.                                 System.out.println("太大");
  23.                                 System.out.println(small + "~" + guess);
  24.                                 big = guess;
  25.                                 total++;
  26.                         } else if (guess < ans) {
  27.                                 System.out.println("太小");
  28.                                 System.out.println(guess + "~" + big);
  29.                                 small = guess;
  30.                                 total++;
  31.                         } else {
  32.                                 System.out.println("GOTCHA!");
  33.                                 System.out.println("一共猜了" + total + "次");
  34.                                 break;
  35.                         }
  36.                 }
  37.         }
  38. }
複製代碼

TOP

返回列表