Java - if / else doesn't work right away when supposed to suspend

I am having problems with a function in java. Here's my code:

    do{
        System.out.print("Proceed to payment? (y/n) ");
        input = scan.nextLine();
        if((input.trim()).equals("y")){
            break;
        }
        else if((input.trim()).equals("n")){
            System.out.print("Come back next time, " + name + ".");
            System.exit(0);
        }
        else{
            System.out.println("Invalid response. Try again.");
        }
    }
    while(true);

      

Basically, on first run, the function "skips" "input = scan.nextLine" and immediately prints "Invalid response. Please try again". to the terminal. It then allows the user to enter something and it works fine.

Yes, I have declared input, scan (java.util.Scanner;) and name earlier in my code. It would be very helpful if someone can point out what I did wrong! Thank!

+3


source to share


2 answers


You probably called scan.next()

or something before entering the loop do-while

. This left the next line character in the input and the call scan.nextLine()

destroyed it. To fix this, you can place a call scan.nextLine()

immediately after scan.next()

so that it uses the next line before entering the loop.

For example:



Scanner scan = new Scanner(System.in);
String input;
String name = scan.next();
scan.nextLine();
do {
    System.out.print("Proceed to payment? (y/n) ");
    input = scan.nextLine();
    // rest of the code
}
while(true);

      

+1


source


While adding scan.nextLine()

, before this helps, I keep the general rule of setting the delimiter whenever I initialize the Scanner class using:

scan.useDelimiter("\n");

      



in this case, that uses the newline character as the delimiter. As a result, for all scan methods, every time the user clicks Enter

it is interpreted as the end of input. This includes nextInt()

, nextDouble()

, next()

etc.

Using a separator also means that I don't have to add no scan.nextLine()

after every login nextLine()

.

+3


source







All Articles