如何让程序在 if 语句之后使用扫描器要求输入?
import java.util.Scanner;
public class App1 {
public static void main(String[] Args) {
Scanner keyboard = new Scanner(System.in);
String gender;
String fName;
String lName;
int age;
String female = "F";
String male = "M";
String a = "";
String gettingMarried = "y";
String notGettingMarried = "n";
System.out.println("What is your gender (M or F)");
gender = keyboard.nextLine();
System.out.println("What is your first name?");
fName = keyboard.nextLine();
System.out.println("What is your last name?");
lName = keyboard.nextLine();
System.out.println("Age:");
age = keyboard.nextInt();
System.out.println();
if (gender.equals(female) && age >= 20) {
System.out.println("Are you married " + fName + " (y or n?)");
a = keyboard.nextLine();
} else if (gender.equals(male) && age >= 20) {
System.out.println("Are you married" + fName + "(y or n?)");
a = keyboard.nextLine();
}
}
}
最佳答案
这是因为您使用的 nextInt()
只接受 int
值,而不是整行。当您再次尝试使用 keyboard.nextLine() 读取时,您捕获到的内容是您放置 int 的行的其余句子。
将 if
语句之前的 System.out.println();
更改为 keyboard.nextLine();
编辑:如果您想要更详细的解释为什么必须在 keyboard.nextInt()
之后放置 keyboard.nextLine();
code>你可以引用我在另一个有同样问题的问题中的回答:Why isn't the scanner input working?
希望对你有帮助!
关于java - 为什么 if 语句后无法输入信息?没有错误显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32193702/