thehollow
thehollow

Reputation: 17

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

Upvotes: 0

Views: 57

Answers (3)

Usagi Miyamoto
Usagi Miyamoto

Reputation: 6299

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...

Upvotes: 0

iperezmel78
iperezmel78

Reputation: 445

Try this:

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

Upvotes: 0

Sachin Kumar
Sachin Kumar

Reputation: 1167

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

Upvotes: 1

Related Questions