简体   繁体   中英

If-else with print statement is skipping scanner

I have this code here but the if-else statement always skips over my second scanner. What am I doing wrong here? I got Login Debit in my console.

public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
    String returnStatement = "";
    System.out.println("Welcome to Hollow gas station! Please let me know whether you are using a debit card or a credit card:\n"
            + "(1) Debit card \n(2) Credit card\n> ");
    int cardType = keyboard.nextInt();
    System.out.println("Awesome! Please enter your card number here: ");

    String cardNum = keyboard.nextLine();
    keyboard.next();
    if(cardType == 1) {
        returnStatement = String.format("Login\t%s\t%s", "Debit", cardNum);
    }
    else if(cardType == 2) {
        returnStatement = String.format("Login\t%s\t%s", "Credit", cardNum);
    }
    else {
        returnStatement = "Error";
    }
    System.out.println(returnStatement);
}

I have gone through with your problem. try this

public static Scanner keyboard = new Scanner(System.in);
    public static void main(String[] args) {
        String returnStatement = "";
        System.out.println("Welcome to Hollow gas station! Please let me know whether you are using a debit card or a credit card:\n"
                + "(1) Debit card \n(2) Credit card\n> ");
        int cardType = Integer.parseInt(keyboard.nextLine());
        System.out.println("Awesome! Please enter your card number here: ");

        String cardNum = keyboard.nextLine();
        //keyboard.next();
        if(cardType == 1) {
            returnStatement = String.format("Login\t%s\t%s", "Debit", cardNum);
        }
        else if(cardType == 2) {
            returnStatement = String.format("Login\t%s\t%s", "Credit", cardNum);
        }
        else {
            returnStatement = "Error";
        }
        System.out.println(returnStatement);
    }

Try this:

...
String cardNum = keyboard.next(); // Use next()
//keyboard.next(); Remove this line
if(cardType == 1) {
...

The problem is that Scanner.nextInt() parses the input until the last character of the number, and then stops. Add a

keyboard.nextLine();

line just to skip to the next line...

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