Java Scanner 输入与 if else 语句

2024-04-21

你好,我是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!");
    }
}

Calling nextLine()消耗扫描仪的一条线。你第一次这样做if,所以后续的else if事实上,分支正在比较以下几行 (or null,如果您没有任何其他输入)。相反,您应该只使用该行一次,将其保存到本地变量并在比较中使用它:

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

话虽如此,使用 if-else 结构并不是最好的解决方案。您可以通过使用来节省大量代码膨胀不区分大小写 https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER TreeSet https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html:

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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java Scanner 输入与 if else 语句 的相关文章

随机推荐