- package main;
- import java.util.Scanner;
- public class Main
- {
- public static void main(String[] args) throws MyException
- {
- int times=0;
- int small=1;
- int big=99;
- int num=(int)(Math.random()*99+1);
- Scanner scanner=new Scanner(System.in);
- int guess=0;
- while(true)
- {
- try
- {
- System.out.println("猜1個介於"+small+"到"+big+"的數:");
- guess=scanner.nextInt();
- }
- catch(Exception ex)
- {
- guess=0;
- }
-
-
- if(guess==num){
- System.out.println("猜對了");
- break;
- }
- else if(guess>num){
- System.out.println("猜得太大了");
- big=guess;
- }else{
- System.out.println("猜的太大了");
- small=guess;
- }
- }
- System.out.println("猜了"+times+"次");
- }
- }
複製代碼 |