簡體   English   中英

為什么我必須輸入兩次整數才能使我的 Scanner 輸入起作用?

[英]Why do I have to put an integer twice for my Scanner input to work?

我正在嘗試制作一個簡單的程序,您可以在其中放入整數,它會告訴您它是從先前的整數輸入增加還是減少。 但是當我運行代碼時,我必須把一個整數值放兩次,但我只希望它放一次。

輸入和輸出應該是這樣的(我輸入的數字,程序輸出的單詞):

Starting...
5
Increasing
4
Decreasing
6
Increasing

等等等等

但它看起來像:

Starting...
5
5
Increasing
Input Number:
1
2
Not Increasing

等等等等

這是我的代碼:

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();
    }
}

為什么會出現此問題,我該如何解決?

您描述的循環行為是:

  • 讀取數字輸入值
  • 用它做點什么(打印一條消息)
  • 如果循環值滿足條件(輸入為 0 或更小),則退出循環
  • 否則,重復

這是一個類似於上述步驟的“do-while”循環:

Scanner scan = new Scanner(System.in);
int input;
do {
    input = scan.nextInt();
    System.out.println("input: " + input);
} while (input > 0);
System.out.println("done");

而這里是輸入+輸出,先輸入“1”,再輸入“0”:

1
input: 1
0
input: 0
done

while (!(scan.nextInt() <= 0)) {接受一個 int 然后input = scan.nextInt(); 需要另一個。 您需要更改 while 循環以使用input

根據您的代碼修改

    public static void main(String[] args) {
        System.out.println("Starting...");
        int input;
        int previousInput = 0;
        Scanner scan = new Scanner(System.in);
        while (true) {
            System.out.println("Input Number:");
            input = scan.nextInt();
            if (input <= 0) {
                System.out.println("app shut down");
                break;
            }
            if (input > previousInput) {
                System.out.println("Increasing");
            } else {
                System.out.println("Not Increasing");
            }
            previousInput = input;
        }
        scan.close();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM