使用if else语句输入Java Scanner

嗨,我是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结构并不是最好的解决方案。 您可以使用不区分大小写的 TreeSet来节省大量代码膨胀:

 TreeSet 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(); } 

人们的事实仍然是,上面提供的答案特别容易让那些对java社区相对较新的人感到困惑。 因此,要求是更容易和更简单的答案。 现在,Java仅通过以下代码了解Strings:

Scanner sc=new Scanner(System.in); String a=sc.next(); if(a.equals("xyzzy")) {System.out.println("yes");