Reputation: 1
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
double dblNumber, dblSquare, dblSqrt;
String answer;
String answery = "yes";
String answern = "no";
while (true) {
System.out.println( "Welcome to Squarez! Where we do the math for you.\nPlease input a number you would like us to do some math with.");
dblNumber = input.nextDouble();
dblSqrt = Math.sqrt(dblNumber);
dblSquare = Math.pow(dblNumber, 3);
System.out.println("" + dblSquare + " " + dblSqrt);
System.out.println("Would you like to continue?");
answer = input.nextLine();
if (answer.equals(answery)) {
System.out.println("You answered yes");
}
if (answer.equals(answern)) {
System.out.println("You answered no.");
System.exit(0);
}
}
}
The program runs and completely ignores the prompt for asking the user if they want to continue. It goes straight back to the prompts for first number. Why is it skipping that?
Upvotes: 0
Views: 2650
Reputation: 128
that's how it should be:
String answer;
String answery = "yes";
String answern = "no";
System.out.println("Would you like to continue?");
input.nextLine();
answer = input.nextLine();
And you just have two decisions to make either "yes" or "no", I don't really see why you used 2 if statements; while you'd have just done this for the Yes part of the answer and the opposite will be a NO.
if(answer.equals(answery))
{
System.out.println("You answered yes");
}
else
System.out.println("You answered no.");
System.exit(0);
Upvotes: 0
Reputation: 20648
You read the number with the statement
dblNumber = input.nextDouble();
Although this line blocks until a whole line - including a newline character - is entered by the user, only the characters without the newline are parsed and returned as a double.
That means, the newline character is still waiting to be retrieved from the scanner! The line
answer = input.nextLine();
directly does exactly that. It consumes the newline character, feeding the variable answer
with an empty string.
So, what's the solution? Use always input.nextLine()
for reading user input and then parse the resulting string in whatever you need:
String line = input.nextLine();
dblNumber = Double.parseDouble(line);
Upvotes: 1
Reputation: 8386
You have to consume the line break after your double:
System.out.println("Would you like to continue?");
input.nextLine(); // <-- consumes the last line break
answer = input.nextLine(); // <-- consumes your answer (yes/no)
Upvotes: 3