Java Scanner input with if else statement

前端 未结 2 1399
悲&欢浪女
悲&欢浪女 2021-01-22 10:45

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

2条回答
  •  -上瘾入骨i
    2021-01-22 11:20

    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...
    

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

提交回复
热议问题