Guess a number program with Java

前端 未结 6 1742
情话喂你
情话喂你 2021-01-28 12:06

I am trying to create a program in Java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number.

If the number is lower

6条回答
  •  天涯浪人
    2021-01-28 12:39

    You forgot to get a new int from the scanner in each loop :)

    import java.util.Scanner;
    
    public class QuestionOne
    {
      public static void main(String args[])
      {
       Scanner keyboard = new Scanner(System.in);
    
       int a = 1 + (int) (Math.random() * 99),
           guess, 
           count = 0;
    
       System.out.println("I am thinking of a number from 1 to 100 ... guess what it is ?");
    
       while((guess = keyboard.nextInt()) != a){
         if (guess > a)
         {  
           System.out.println("lower!");
         }
         else
         {
           System.out.println("higher!");
         }
         count++;
       }
    
       System.out.println("Congratulations.   You guessed the number with "+ count +" tries!");
      }
    
    }
    

    edit : I'm currently bored... Add the counter ;)

提交回复
热议问题