【问题标题】:Why do I have to put an integer twice for my Scanner input to work?为什么我必须输入两次整数才能使我的 Scanner 输入起作用?
【发布时间】:2022-07-06 11:22:34
【问题描述】:

我正在尝试制作一个可以放入整数的简单程序, 它会告诉你它是否比以前增加或减少 整数输入。但是当我在 IntelliJ 中运行它时,我必须放一个 整数值两次,但我只想放一次。

例子:

所需的输出:

开始...

5

增加

4

减少

6

增加

等等。等等

但我必须这样做才能让它响应:

开始...

5

5

增加

输入号码:

1

2

没有增加

等等。等等

import java.util.Scanner;

public class Prob1 {
    public static void main(String[] args) {
        System.out.println("Starting...");
        int input;
        int previousInput = 0;
        Scanner scan = new Scanner(System.in);
        while (!(scan.nextInt() <= 0)) {
            input = scan.nextInt();
            if (input > previousInput) {
                System.out.println("Increasing");
                previousInput = input;

            } else {
                System.out.println("Not Increasing");
                previousInput = input;
            }
            System.out.println("Input Number:");
        }
        scan.close();
    }
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。请尝试仔细考虑代码,一次一步。上面写着while (!(scan.nextInt() &lt;= 0)) {,你希望它做什么?上面写着input = scan.nextInt();,你希望它做什么?在这两行代码之间,你看到了多少次代码scan.nextInt()?当你运行代码时,你需要输入多少次数字?你看到相关性了吗?
  • 它的写法,在while语句中有一个scan.nextInt(),所以先运行,然后如果其余的条件为真(所以,如果!(scan.nextInt() &lt;= 0)返回“真") 下一行是另一个scan.nextInt()。每次通过循环,都会发生同样的事情——while 条件,然后在循环内再发生一个。

标签: java java.util.scanner


【解决方案1】:

while (!(scan.nextInt() &lt;= 0)) { 接受一个 int,然后 input = scan.nextInt(); 接受另一个。您需要更改 while 循环以使用 input

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多