我需要在 Java 中使用 if else-if else 语句(老实说不是我的第一选择),除了所有第二个语句总是需要输入两次之外,所有语句都可以正常工作。
即:“输入 A 或 B。” A 在第一次输入时起作用。 B 必须输入两次。
public static void exampleMethod(){
if(input.next().equals("A")){
System.out.println("This is said when A is input.");
}
else if(input.next().equals("B")){
System.out.println("This is said when B is input");
}
else
exampleMethod(); //returns to top of method;
}
否则代码工作正常,“B”下的所有内容在输入两次后都会运行,但我需要它工作,以便它在第一次输入时注册 B,而不必输入“B”然后输入“B”再次让它运行。开关也会出现这种情况 像:
switch(input.next()){
case "A":
System.out.println("A pressed");
break;
case "B":
System.out.println("B pressed");
break;
default:
exampleMethod();
}
这是令人烦恼的 Java 时刻之一吗?因为我用 C# 做过类似的事情,而且效果很好。
最佳答案
正如 @MattJones 所说,input.next()
读取输入,因此您不应直接在 if else block 中使用它。
而是读取值,然后执行 if/then
public static void exampleMethod() {
String inputValue = input.next();
if (inputValue.equals("A")) {
System.out.println("This is said when A is input.");
} else if (inputValue.equals("B")) {
System.out.println("This is said when B is input");
} else {
exampleMethod(); // returns to top of method;
}
}
关于java - 我必须输入相同的字符串两次才能运行 'else if' 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50353206/