Reputation: 15
I'm having an issue where my program is skipping a prompt for user input. The relevant code is below:
System.out.format("Purchase price is $" + "%.2f%n", sum);
System.out.println("Proceed to payment? (y/n) ");
String proceed = keyboard.nextLine();
while(!proceed.equals("n") && (!proceed.equals("y"))) {
System.out.println("Invalid response. Try again.");
System.out.println("Proceed to payment? (y/n) ");
proceed = keyboard.nextLine();
if (proceed.equals("n")) {
System.out.println("Come back next time, " + name + ".");
System.exit(0);
}
else if (proceed.equals("y")) {`
The output should pause at:
Purchase price is $x.00
Proceed to payment? (y/n)
But instead outputs:
Purchase price is $x.00
Proceed to payment? (y/n)
Invalid response. Try again.
Proceed to payment? (y/n)
Would anyone be able to tell me why its ignoring the first scanner prompt?
EDIT: The code works in isolation, the problem is somewhere else inside the program. When I figure it out I'll report back.
Upvotes: 0
Views: 45
Reputation: 48258
This logic in the while loop condition is wrong
while(!proceed.equals("n") && (!proceed.equals("y"))) {
must be
while(!proceed.equals("n") || (!proceed.equals("y"))) {
if you want to keep your logic with the AND condition then MOVE the payment out of the while so that can work
while (!proceed.equalsIgnoreCase("n") && (!proceed.equalsIgnoreCase("y"))) {
System.out.println("Invalid response. Try again....");
proceed = keyboard.nextLine();
}
if (proceed.equalsIgnoreCase("n")) {
System.out.println("Come back next time, " + name + ".");
System.exit(0);
} else if (proceed.equalsIgnoreCase("y")) {
System.out.println("now we are going to pay, " + name + "." + sum);
System.exit(0);
}
Upvotes: 3