gpt4 book ai didi

带有 if else 语句的 Java Scanner 输入

转载 作者:行者123 更新时间:2023-11-30 10:40:43 25 4
gpt4 key购买 nike

大家好,我是 Java 的新手,正在尝试做一个测验来练习。我想提出一个问题,用户必须将单词从类别组合到对。像 A1 B4 C3 D2。我现在所做的是使用 if else 语句来检查输入是否为正确答案,但它仅适用于 1A。对于其他人,我可以做 6 个输入,这不是我想要的,即使有一个正确的输入,我也没有得到一分。

public class HelloWorld {

public static void main(String[] args) {

Scanner walther = new Scanner(System.in);

String cro = "1A";
String dan = "2C";
String fin = "4D";
String dut = "3F";
String fre = "5B";
String ger = "6E";
int x = 0;


if (cro.equalsIgnoreCase(walther.nextLine())){
++x;
walther.close();
}
else if (dan.equalsIgnoreCase(walther.nextLine())){
++x;
walther.close();
}
else if (fin.equalsIgnoreCase(walther.nextLine())){
++x;
walther.close();
}
else if (dut.equalsIgnoreCase(walther.nextLine())){
++x;
walther.close();
}
else if (fre.equalsIgnoreCase(walther.nextLine())){
++x;
walther.close();
}
else if (ger.equalsIgnoreCase(walther.nextLine())){
++x;
walther.close();
}
else {
walther.close();
}

System.out.println(x + " Point!");
}
}

最佳答案

调用 nextLine() 消耗扫描器中的一行。您在第一个 if 上执行此操作,因此随后的 else if 分支实际上是在比较以下行(或 null ,如果您没有任何额外的输入)。相反,您应该只使用一次该行,将其保存到局部变量并在比较中使用它:

String input = walther.nextLine();
if (cro.equlasIgnoreCase(input)) { // etc...

话虽如此,使用 if-else 结构并不是最好的解决方案。使用 case insensitive 可以节省大量代码膨胀TreeSet :

TreeSet<String> set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
set.addAll(Arrays.asList("1A", "2C", "4D", "3F", "5B", "6E"));
String input = walther.nextLine();
if (set.contains(input)) {
++x;
walther.close();
}

关于带有 if else 语句的 Java Scanner 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38802204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com