If-else与打印语句跳过扫描仪

问题描述 投票:0回答:1

我这里有这段代码,但if-else语句总是跳过我的第二个扫描器。我在这里做错了什么?我得到了 Login Debit 在我的控制台中。

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);
}
java if-statement java.util.scanner
1个回答
1
投票

我已经解决了你的问题,试试这个。

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

0
投票

试试这个。

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

0
投票

问题是... Scanner.nextInt() 解析输入,直到数字的最后一个字符,然后停止。添加一个

keyboard.nextLine();

行,只是为了跳到下一行... ...

© www.soinside.com 2019 - 2024. All rights reserved.