返回列表 發帖
  1. import java.util.Scanner;
  2. public class ch17
  3. {
  4.     public static void main(String args[])
  5.     {
  6.          
  7.          int start=1,end=99,count=0;
  8.          int ans=(int)(Math.random()*99+1);
  9.          int guess;
  10.          while(true)
  11.          {
  12.              try
  13.              {
  14.                  Scanner c=new Scanner(System.in);
  15.                  count++;
  16.                  System.out.print("猜一個"+start+"~"+end+"之間的數字: ");
  17.                  guess=c.nextInt();
  18.                  if(guess>ans)
  19.                  {
  20.                      end=guess-1;
  21.                  }else if(guess<ans)
  22.                  {
  23.                      start=guess+1;
  24.                  }else
  25.                  {
  26.                      System.out.println("恭喜你猜對了!");
  27.                      System.out.println("總共猜了"+count+"次!");
  28.                      break;
  29.                  }
  30.              }catch(Exception e)
  31.              {
  32.                  System.out.println("輸入錯誤!請輸入整數!");
  33.              }
  34.          }
  35.     }
  36. }
複製代碼

TOP

返回列表