- package test;
- import java.util.Scanner;
- public class Test{
- 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;
- }
- }
- }
- }
複製代碼 |