dimanche 26 avril 2015

Java - if/else fails immediately when supposed to pause

I'm having troubles 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, the first time the function loops it 'skips' the "input = scan.nextLine" and immediately prints "Invalid response. Try again." to the terminal. It then allows the user to input something, and works normally.

Yes, I have declared input, scan (java.util.Scanner;), and name earlier in my code. It'd be a great help if someone can point out what I've done wrong! Thanks!

Aucun commentaire:

Enregistrer un commentaire