返回列表 發帖
  1. import java.util.Scanner;
  2. public class Ch01
  3. {
  4.         public static void main(String[] args)
  5.         {   
  6.                 Scanner sc=new Scanner(System.in);
  7.                 int a=1,b=99,ans,n=0;
  8.                 double r=(int)(Math.random()*99+1);
  9.                 while(true)
  10.                 {
  11.                         n++;
  12.                         if(a==b)
  13.                         {
  14.                                 System.out.println("可惜了,答案是"+r);
  15.                                 break;
  16.                         }

  17.                         System.out.println("猜一個"+a+"~"+b+"之間的數:");
  18.                         ans=sc.nextInt();
  19.                         if(ans<r)
  20.                         {
  21.                                 if(ans<a)
  22.                                 {
  23.                                         System.out.println("是在哈囉?");
  24.                                 }
  25.                                 else
  26.                                 {
  27.                                         System.out.println("猜得太小");
  28.                                         a=ans+1;
  29.                                 }       
  30.                         }

  31.                         else if(ans>r)
  32.                         {
  33.                                 if(ans>b)
  34.                                 {
  35.                                         System.out.println("是在哈囉?");
  36.                                 }
  37.                                 else  
  38.                                 {
  39.                                         System.out.println("猜得太大");
  40.                                         b=ans-1;
  41.                                 }
  42.                         }
  43.                         else
  44.                         {
  45.                                 System.out.println("答對了");
  46.                                 break;
  47.                         }


  48.                 }
  49.                 System.out.println("總共猜了"+n+"次");
  50.         }

  51. }
複製代碼

TOP

返回列表