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

问题描述 投票:1回答:1

如果我输入'0','1','2'或'3'(按特定顺序),程序的输出是完美的。如果我以不同的顺序输入整数,代码将无法正常工作。例如,如果我先选择'2',我的代码要求我输入整数三次,以便为我提供正确的输出。有人可以让我知道我做错了什么吗?

我尝试过使用else-if语句,当我输入除“0”以外的任何内容时,我需要输入整数等于索引号的整数。例如,如果我输入'2',我必须输入它总共三次以获得我想要的输出。

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
java output java.util.scanner
1个回答
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循环的每次运行获取输入,它将按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.