samedi 6 janvier 2018

Random number generator with user input code doesn't work correctly

another beginner question from me. I apologize in advance, but could you please help me out here? So I want to create this random number generator which will generate numbers 1-100 and ask for user input. The user ought to guess until (s)he finally gets the right number. At the end, the program should print "you guessed from xx attempt". So the problem is, when I tested the code, twice it ran correctly, and other 2 times it was wrong (the number of attempts was shown wrong). Now also I feel the code could be written in a much better way, but don't know exactly how.Thanks

import java.util.Scanner;
import java.util.Random;
public class JavaApplication2018 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number, please");
        int attempt = input.nextInt();
        Random dice = new Random();
        int number;
        number = dice.nextInt(100) + 1;
        int counter = 0;
       while (number > attempt) 
       {
           System.out.println("I imagined a bigger number. Guess again!");
           attempt = input.nextInt();
           counter++;
       }

       while (number < attempt)
       {
           System.out.println("I imagined a smaller number. Guess again!");
           attempt = input.nextInt();
           counter++;
       }

       if (number == attempt)
       {

           counter++;
       }


       System.out.println("You guessed from " + counter +". attempt" );

    }  


}




Aucun commentaire:

Enregistrer un commentaire