• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java question...

Joony

Diamond Member
Why does "yes or no?" get printed out twice before asking me for an input? (EasyReader is a thing that reads exactly what you type in)

public class CandyApp
{
public static void main (String args[])
{
int players;
boolean playgame = true;
String command;
EasyReader console = new EasyReader();
System.out.println("\nEnter Number of Players:");
players = console.readInt();
int player[] = new int[players];
for (int i = 0; i < players; i++)
{
System.out.println("\nHow many candies for player " + (i + 1) + "?");
player = console.readInt();
}
while (playgame == true)
{
System.out.println("yes or no?");
command = console.readLine();
if (command.equals("no"))
playgame = false;
}
}
}
 
<- Java newb...

right...so (too much technical jargon), what does that mean and how do i fix it?
 
When someone types in a number after the "Enter Number of Players" prompt, they enter a number, and then a newline character (the enter key). Later on, you read a number from the input, and that gets rid of the number. You still have a newline character left in the input pipe, and so when you run readLine the fist time, it reads up through the first newline character, which is the first character in the pipe. So it jsut reads "\n" into command, and since "\n" isn't "no", it loops through the while loop again.
 
Based on notfred's extremely perceptive reply, here are two simple solutions:
1) Empty out your console input buffer before you begin the while loop (not sure what method you invoke, perhaps console.reset(), console.empty(), console.flush() ... all of which are guesses, I looked none of them up).
-or-
2) Change statement "players = console.readInt();" to use a console.readLine() and then convert the read line to integer.

 
yes, you're best best would be an Integer.parseInt(console.readLine()).

Just remember to handle the NumberFormatException!
 
Back
Top