- import java.util.Scanner;
- public class Ch01 {
- public static void main(String[] args) {
- int x=(int)(Math.random()*99+1);
- int sum=1, ans, a=1, b=99;
- System.out.println(x);
- while(true)
- {
- Scanner s=new Scanner(System.in);
- System.out.print("猜一個"+a+"~"+b+"的數字: ");
- ans=s.nextInt();
- try{
- if(ans<x)
- {
- System.out.println("猜得太小");
- sum++;
- a=ans+1;
- }
- else if(ans>x)
- {
- System.out.println("猜得太大");
- sum++;
- b=ans-1;
- }
- else
- {
- System.out.println("猜對了!!!!!!!!!!!!!!!!!!!!!!!");
- break;
- }
- }catch(Exception e)
- {
- System.out.println("請輸入一整數!!!!!!!!!!!");
- }
- }
- System.out.println("總共猜了"+sum+"次");
- }
- }
複製代碼 |