嗨,我是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()
会占用扫描仪中的线路。您在first上执行此操作if
,因此else if
,实际上,后续分支将比较以下各行(null
如果没有任何其他输入,则比较)。相反,您只应使用该行一次,将其保存到本地变量,然后在比较中使用它:
String input = walther.nextLine();
if (cro.equlasIgnoreCase(input)) { // etc...
话虽这么说,使用和if-else结构并不是最简洁的解决方案。通过使用不区分大小写 的代码,您可以节省很多代码膨胀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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句