【发布时间】:2019-04-06 18:12:22
【问题描述】:
如果我输入“0”、“1”、“2”或“3”(按特定顺序),程序的输出是完美的。如果我以不同的顺序输入整数,代码将无法正常工作。例如,如果我首先选择“2”,我的代码希望我输入整数总共 3 次,以便给我正确的输出。有人可以告诉我我做错了什么吗?
我尝试过使用 else-if 语句,当我输入除 '0' 以外的任何内容时,我需要输入整数的总次数等于索引号。例如,如果我输入'2',我必须总共输入3次才能得到我想要的输出。
System.out.println("Please input a number between zero to 3");
for (int i = 0; i < 4; i++) {
if (sc.nextInt() == 0) {
System.out.println("You have selected " + right);
}
if (sc.nextInt() == 1) {
System.out.println("You have selected " + left);
}
if (sc.nextInt() == 2) {
System.out.println("You have selected " + up);
}
if (sc.nextInt() == 3) {
System.out.println("You have selected " + down);
break;
}
}
我的预期输出应该是:
This program simulates the 4 arrows RIGHT, LEFT, UP, DOWN using the numbers 0, 1, 2, 3 respectively Please input a number between zero to 3 3 You have selected DOWN 1 You have selected LEFT 0 You have selected RIGHT 2 You have selected UP Process finished with exit code 0
当我将它们按正确的顺序放置时,就会发生此输出。如果我从输入“1”开始,就会发生这种情况:
This program simulates the 4 arrows RIGHT, LEFT, UP, DOWN using the numbers 0, 1, 2, 3 respectively Please input a number between zero to 3 1 1 You have selected LEFT
【问题讨论】:
-
您在每个
if语句中都调用了nextInt()。想想那有什么作用。 -
我的理解(这是有限的)是我调用 nextInt() 是因为我正在寻找来自扫描仪的特定整数输入。
-
将输入保存到变量中:int direction = sc.nextInt();并对该变量进行 if 检查。
-
nextInt()使用它返回的输入。如果你调用它 4 次,它将期望来自标准输入的 4 个整数。
标签: java output java.util.scanner