【问题标题】:How to fix print output when integers are input输入整数时如何修复打印输出
【发布时间】: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


【解决方案1】:

将您的逻辑更改为:

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 循环的 每个 运行获取输入,它将按预期工作。

【讨论】:

  • 这似乎有效,但是,它不允许我总共输入 4 次整数。代码将在一次输入后“中断”并结束。
  • 确实如此。此外,这可能与 break 语句有关(取决于您提供的 what 输入。)
  • 我刚刚意识到,如果我删除 'break' 语句,代码会在 4 次尝试后运行并终止。谢谢你的帮助!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
相关资源
最近更新 更多