输入整数时如何修复打印输出

时间:2019-04-06 18:12:23

标签: java output java.util.scanner

如果我输入“ 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

1 个答案:

答案 0 :(得分:3)

将逻辑更改为:

for (int i = 0; i < 4; i++) {
    System.out.println("Please input a number between zero to 3");
    // use input and don't advance the scanner every time
    int input = sc.nextInt();

    if (input == 0) {
        System.out.println("You have selected " + right);
    }
    if (input == 1) {
        System.out.println("You have selected " + left);
    }

    // so on and so forth

}

通过使用sc.nextInt() 四次次,您正在寻找输入中不存在的下一个标记。因此,获取for循环的每个运行的输入,它将按预期工作。