返回列表 發帖
  1. package main;

  2. import java.util.Scanner;

  3. public class Main
  4. {
  5.         public static void main(String[] args) throws MyException
  6.         {
  7.                 int times=0;
  8.                 int small=1;
  9.                 int big=99;
  10.                 int num=(int)(Math.random()*99+1);
  11.                 Scanner scanner=new Scanner(System.in);
  12.                 int guess=0;
  13.                 while(true)
  14.                 {
  15.                     try
  16.                     {
  17.                            System.out.println("猜1個介於"+small+"到"+big+"的數:");
  18.                     guess=scanner.nextInt();
  19.                     }   
  20.                         catch(Exception ex)
  21.                         {
  22.                                 guess=0;
  23.                         }
  24.                        
  25.                        
  26.                         if(guess==num){
  27.                                 System.out.println("猜對了");
  28.                                 break;
  29.                         }
  30.                         else if(guess>num){
  31.                                 System.out.println("猜得太大了");
  32.                                 big=guess;
  33.                         }else{
  34.                                 System.out.println("猜的太大了");
  35.                                 small=guess;
  36.                         }                                       
  37.                 }
  38.                 System.out.println("猜了"+times+"次");
  39.         }
  40. }
複製代碼

TOP

返回列表