返回列表 發帖

猜數字遊戲 (二)

本帖最後由 tonyh 於 2012-9-22 17:06 編輯

改良上一個程式碼, 讓使用者重覆猜測時, 範圍能越縮越小,
譬如一開始顯示"猜一個1~99間的數字", 當使用者猜56後, 訊息能變成"猜一個1~56間的數字",
當使用者再猜22後, 訊息又會變成"猜一個22~56間的數字".
  1. import java.io.Console;
  2. public class ch29
  3. {
  4.     public static void main(String args[])
  5.     {
  6.           Console console=System.console();
  7.           String str;
  8.           int a=1, b=99;
  9.           int ans=38;
  10.           int guess;
  11.           while(true)
  12.           {
  13.                System.out.print("猜一個"+a+"~"+b+"之間的數字: ");
  14.                guess=Integer.parseInt(console.readLine());
  15.                a=(guess<ans)?guess:a;
  16.                b=(guess>ans)?guess:b;
  17.                if(guess!=ans)
  18.                {
  19.                     str=(guess>ans)?"猜得太大了":"猜得太小了";
  20.                     System.out.println(str);
  21.                     continue;
  22.                }
  23.                break;
  24.           }
  25.           System.out.println("恭喜你猜對了!");
  26.     }
  27. }
複製代碼

返回列表