- import java.util.Scanner;
- public class B
- {
- public static void main(String[] args)
- {
- Scanner s=new Scanner(System.in);
- int a=1,b=99;
- int n=0;
- int ans=(int)(Math.random()*99+1);
- int guess;
- while(true)
- {
- n++;
- System.out.print("猜一個"+a+"~"+b+"之間的數字:");
- guess=s.nextInt();
- if(guess>ans)
- {
- System.out.println("太大");
- b=guess-1;
- }else if(guess<ans)
- {
- System.out.println("太小");
- a=guess+1;
- }
- else
- {
- System.out.println("恭喜你猜對了!");
- System.out.println("總共猜了"+n+"次");
- break;
- }
- }
- }
- }
複製代碼 |