0

I've been getting frustrated because my input is being skipped by the program for some reason. This causes the while loop to be skipped and the program to stop.

    public static void main(String[] args) 
{
    Scanner input = new Scanner(System.in);
    Random random = new Random();

    System.out.println("Guess a number between 1 and 10.");
    int count = 1;
    int guess = input.nextInt();
        int answer = random.nextInt(1) + 1;

    while(guess != answer)
    {
        System.out.println("Wrong answer. Try again.");
        guess = input.nextInt();
        count++;
    }
    System.out.println("\nIt took " + count + " guesses to guess " + answer + ".");
    System.out.println("\nWould you like to play again (Y/N)?");
            String decision = input.nextLine(); // The program skips this input
            decision = decision.toUpperCase();
        while(decision.equals("Y"))
        {
    System.out.println("Guess a number between 1 and 10.");
    count = 1;
    guess = input.nextInt();
        answer = random.nextInt(1) + 1;

    while(guess != answer)
    {
        System.out.println("Wrong answer. Try again.");
        guess = input.nextInt();
        count++;
    }
    System.out.println("\nIt took " + count + " guesses to guess " + answer + ".");
    System.out.println("\nWould you like to play again (Y/N)?");
            decision = input.nextLine();
            decision = decision.toUpperCase();                
        }    
System.out.println("Thanks for playing.");
}
Raulz
  • 19
  • 2
    There's probably still a new line in the buffer from when you read it using `nextInt` – MadProgrammer Mar 05 '16 at 05:08
  • 1
    read again from the docs the difference b/w `next()` and `nextLine()` – singhakash Mar 05 '16 at 05:09
  • Possible duplicate of [Skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – NikolayK Mar 05 '16 at 05:59

0 Answers0