- import java.util.Scanner;
- public class Ch01
- {
- public static void main(String[] args)
- {
- Scanner sc=new Scanner(System.in);
- int ans=(int)(Math.random()*99+1);
- int n,a=1,b=99,x=0;
- while(true)
- {
- x++;
- System.out.println("猜一個"+a+"~"+b+"之間的數字: ");
- n=sc.nextInt();
- if(n>ans)
- {
- if(n<a || n>b)
- {
- System.out.println("問號?");
- continue;
- }
- System.out.println("猜的太大了!");
- b=n-1;
- }
- else if(n<ans)
- {
- if(n<a || n>b)
- {
- System.out.println("問號?");
- continue;
- }
- System.out.println("猜的太小了!");
- a=n+1;
- }
- else
- {
- System.out.println("恭喜您猜對了!");
- System.out.println("猜了"+x+"次");
- break;
- }
- if (a==b)
- {
- System.out.println("可惜了,答案是"+ans);
- return;
- }
- }
- }
- }
複製代碼 |