[英]If-else with print statement is skipping scanner
I have this code here but the if-else statement always skips over my second scanner.我在这里有这段代码,但 if-else 语句总是跳过我的第二个扫描仪。 What am I doing wrong here?
我在这里做错了什么? I got
Login Debit
in my console.我在控制台中获得了
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);
}
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.问题是
Scanner.nextInt()
解析输入直到数字的最后一个字符,然后停止。 Add a添加一个
keyboard.nextLine();
line just to skip to the next line...行只是跳到下一行...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.