返回列表 發帖
  1. import java.util.Scanner;
  2. public class Ch01 {
  3.         public static void main(String[] args) {
  4.                 int a=1,b=99;
  5.                 int guess,n=0;
  6.                 int target=(int)(Math.random()*99+1);
  7.                 while(true)
  8.                 {
  9.                         n++;
  10.                         Scanner s=new Scanner(System.in);
  11.                         System.out.print("猜一介於"+a+"~"+b+"間的數字:");
  12.                         try
  13.                         {
  14.                                 guess=s.nextInt();
  15.                                 if(guess>target)
  16.                                 {
  17.                                         System.out.println("猜得太大了");
  18.                                         b=guess-1;
  19.                                 }
  20.                                 else if(guess<target)
  21.                                 {
  22.                                         System.out.println("猜得太小了");
  23.                                         a=guess+1;
  24.                                 }
  25.                                 else
  26.                                 {
  27.                                         System.out.println("恭喜你,答對了!");
  28.                                         break;
  29.                                 }

  30.                         }catch(Exception e)
  31.                         {
  32.                                 System.out.println("請輸入一整數!");
  33.                         }
  34.                 }
  35.                 System.out.println("總共花了"+n+"次!");
  36.         }
  37. }
複製代碼

TOP

返回列表