Note that there are some explanatory texts on larger screens.

plurals
  1. POJava .nextLine() repeats line
    primarykey
    data
    text
    <p>Everything of my guessing game is alright, but when it gets to the part of asking the user if he/she wants to play again, it repeats the question twice. However I found out that if I change the input method from nextLine() to next(), it doesn't repeat the question. Why is that?</p> <p>Here is the input and output:</p> <pre><code>I'm guessing a number between 1-10 What is your guess? 5 You were wrong. It was 3 Do you want to play again? (Y/N) Do you want to play again? (Y/N) n </code></pre> <p>Here is the code:(It is in Java) The last do while loop block is the part where it asks the user if he/she wants to play again. </p> <pre><code>import java.util.Scanner; public class GuessingGame { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean keepPlaying = true; System.out.println("Welcome to the Guessing Game!"); while (keepPlaying) { boolean validInput = true; int guess, number; String answer; number = (int) (Math.random() * 10) + 1; System.out.println("I'm guessing a number between 1-10"); System.out.print("What is your guess? "); do { validInput = true; guess = input.nextInt(); if (guess &lt; 1 || guess &gt; 10) { validInput = false; System.out.print("That is not a valid input, " + "guess again: "); } } while(!validInput); if (guess == number) System.out.println("You guessed correct!"); if (guess != number) System.out.println("You were wrong. It was " + number); do { validInput = true; System.out.print("Do you want to play again? (Y/N) "); answer = input.nextLine(); if (answer.equalsIgnoreCase("y")) keepPlaying = true; else if (answer.equalsIgnoreCase("n")) keepPlaying = false; else validInput = false; } while (!validInput); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload