- import java.util.Scanner;
- import java.util.Random;
- class Ch01
- {
- public static void main(String[] args)
- {
- Scanner s = new Scanner(System.in);
- int a=1, b=99,ans,n=0;//a= lowest value, b = highest value, ans is the variable we are trying to guess, n is the guesscount
- int r=(int)(Math.random()*99+1); //value we are trying to guess
- while(true)
- {
- n++;
- if(a==b)//if the range for the answer is still the same you print the answer
- {
- System.out.println("Oof the correct answer is "+r);
- break;
- }
- System.out.println("guess a value between "+a+"~"+b);
- ans=sc.nextInt(); //input for the guessed number
- if(ans<r)//
- {
-
- a=ans+1;
- if(ans<a)
- {
- System.out.println("?! What");
- }
- else
- {
- System.out.println("The value you guessed was too small ");
- a=ans+1;
- }
- }
- else if(ans>r)//50>30
- {
-
- if(ans>b)
- {
- System.out.println("?! what");
- }
- else
- {
- System.out.println("the value is too big");
- b=ans-1;
- }
- b=ans-1;
- }
- else
- {
- System.out.println("You got the answer right! ");
- break;
- }
- }
- System.out.println("You guessed in total of"+n+" times");;
- }
- }
複製代碼 |