简体   繁体   中英

Program doesnt wait to ask for user input

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.

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

Example:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM