Sunday, 19 March 2017

loops - Simple Java Scanner code not working





Here is the skeleton of some basic code I am writing to make a simple game:



    Scanner in = new Scanner(System.in);

String name;
String playing;

int age;

do {

System.out.println("Enter your name");
name = in.nextLine();

System.out.println("Enter your age");
age = in.nextInt();


System.out.println("Play again?");
playing = in.nextLine();

} while (true);


The code does not work as expected, for example, here is the expected functioning of the code:



Enter your name
John

Enter your age
20
Play again?
Yes
Enter your name
Bill
...


However, there is an issue with reading the Play again line, this is the actual output:




Enter your name
John
Enter your age
20
Play again?
Enter your name


As you can see "Enter your name" is being displayed again before "Play again?" is able to accept input. When debugging the playing variable is set to "", so there is no input that I can see and I cannot figure out what is being consumed.

Any help would be appreciated, thanks!


Answer



nextInt() doesn't consume the end-of-line, even if the int is the only thing in there.



Add another nextLine() after reading the int, and either discard its value completely, or check that it is empty if you want to prevent people from entering anything but an int.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...