- import java.math.MathContext;
- import java.util.Scanner;
- public class Ch30 {
- public static void main(String[] args) {
- int gu,b=1,c=99,n=0;
- int y=(int)(Math.random()*100);
- while(true)
- {
- Scanner s=new Scanner(System.in);
- n++;
- try{System.out.println("輸入一個"+b+"~"+c+"的數");
- gu=s.nextInt();
- if(gu<y)
- {
- System.out.println("輸入太小了");
- b=gu+1;
- }
- else if(gu>y)
- {
- System.out.println("輸入太大了");
- c=gu-1;
- }
- else
- {
- System.out.println("猜對了");
- break;
- }
- }catch(Exception e)
- {
- System.out.println("輸入整數!");
- }
- }
- System.out.println("共輸入"+n+"次");
- }
- }
複製代碼 |