返回列表 發帖
  1. import java.util.Scanner;
  2. import java.util.Random;
  3. class Ch01
  4. {
  5.     public static void main(String[] args)
  6.     {
  7.         Scanner s = new Scanner(System.in);
  8.         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
  9.         int r=(int)(Math.random()*99+1); //value we are trying to guess
  10.         while(true)
  11.         {
  12.             n++;
  13.             if(a==b)//if the range for the answer is still the same you print the answer
  14.             {
  15.                 System.out.println("Oof the correct answer is "+r);
  16.                 break;
  17.             }
  18.             System.out.println("guess a value between "+a+"~"+b);
  19.             ans=sc.nextInt(); //input for the guessed number
  20.             if(ans<r)//
  21.             {
  22.                
  23.                 a=ans+1;
  24.                 if(ans<a)
  25.                 {
  26.                     System.out.println("?! What");
  27.                 }
  28.                 else
  29.                 {
  30.                     System.out.println("The value you guessed was too small ");
  31.                     a=ans+1;
  32.                 }
  33.             }
  34.             else if(ans>r)//50>30
  35.             {
  36.                
  37.                 if(ans>b)
  38.                 {
  39.                     System.out.println("?! what");
  40.                 }
  41.                 else
  42.                 {
  43.                     System.out.println("the value is too big");
  44.                     b=ans-1;
  45.                 }
  46.                 b=ans-1;

  47.             }
  48.             else
  49.             {
  50.                 System.out.println("You got the answer right! ");
  51.                 break;
  52.             }


  53.         }
  54.         System.out.println("You guessed in total of"+n+" times");;

  55.     }

  56. }
複製代碼

TOP

返回列表