这里是 Java 新手。我编写了以下简单的代码,要求用户在选项 1 或 2 之间进行选择。如果所选选项是 1,那么它应该打印“You said hi”,效果很好,如果所选选项是 2,它应该打印“你说了再见”,但事实并非如此,我在这里错过了什么吗?也许 If 语句是错误的?
代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type 1 to say hi");
System.out.println("Please type 2 to say goodbye");
if (input.nextInt() == 1) {
System.out.println("You said hi");
} else if (input.nextInt() == 2) {
System.out.println("you said goodbye");
}
}
最佳答案
每次调用 nextInt()
时,它都会停止等待 int
。在这里,您想要将用户的单个 int
与一个或两个进行比较。保存您从用户处获得的 int
。就像,
int v = input.nextInt();
if (v == 1) {
System.out.println("You said hi");
} else if (v == 2) {
System.out.println("you said goodbye");
}
关于java - 为什么我的扫描程序不能使用 2 个不同的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59921687/