返回列表 發帖
  1. import java.util.Scanner;
  2. public class Ch01 {

  3.         public static void main(String[] args)
  4.         {
  5.                 int x=(int)(Math.random()*99+1);
  6.                 int        y, n=0;
  7.                 int a=1, b=99;
  8.                 while(true)
  9.                 {               
  10.                         try
  11.                         {
  12.                                 Scanner s=new Scanner(System.in);
  13.                                 n++;
  14.                                 System.out.print("猜一個"+a+"~"+b+"之間的數: ");
  15.                                 y=s.nextInt();
  16.                                 if(y<x)
  17.                                 {       
  18.                                         System.out.println("太小了!");
  19.                                         a=y+1;
  20.                                 }else if(y>x)
  21.                                 {
  22.                                         System.out.println("太大了!");
  23.                                         b=y-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. }
複製代碼

TOP

返回列表