使用if else语句输入Java Scanner [英] Java Scanner input with if else statement
问题描述
您好我是java的新手并且正在尝试进行测验。我想提出一个问题,用户必须将单词中的单词组合成对。像A1 B4 C3 D2一样。我现在做的是使用if else语句来检查输入是否是正确的答案,但它只适用于1A。对于其他人,我可以做6个输入,这不是我想要的,即使有正确的输入,我也没有意见。
Hi I'm new to java and trying to make a Quiz to practice. I wanna make a Question where the user has to combine words from to categories to pairs. Like A1 B4 C3 D2. What I did now is using an if else statement to check if the input is the correct answer, but it only works with 1A. For the others I can do 6 inputs, which is not what I want, and even if there's a correct one I don't get a point.
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
,如果您没有任何其他输入)。相反,您应该只使用该行一次,将其保存到本地变量并在比较中使用它:
Calling nextLine()
consumes a line from the scanner. You do this on the first if
, so the subsequent else if
branches are, in fact, comparing the following lines (or null
, if you don't have any additional input). Instead, you should consume the line only once, save it to a local variable and use that in your comparisons:
String input = walther.nextLine();
if (cro.equlasIgnoreCase(input)) { // etc...
拥有说,使用和if-else结构不是最好的解决方案。使用可以节省大量代码膨胀不区分大小写 TreeSet
:
Having said that, using and if-else structure isn't the neatest solution. You can save a lot of code bloat by using a 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!