java scanner输入语句,使用if else语句输入Java Scanner

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!");

}

}

解决方案

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值