简体   繁体   中英

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

I'm trying to make a simple program where you can put integers in, and it will tell you if it increased or decreased from the previous integer input. But when I run the code, I have to put an integer value twice, but I only want it put once.

The input and output should look like (numbers typed by me, words output by the program):

Starting...
5
Increasing
4
Decreasing
6
Increasing

etc. etc.

But instead it looks like:

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

etc. etc.

This is my code:

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

Why does this problem occur, and how can I fix it?

The loop behavior you are describing is:

  • read a numeric input value
  • do something with it (print a message)
  • if the loop value meets a condition (input is 0 or less), exit the loop
  • otherwise, repeat

Here's a "do-while" loop that reads like those steps above:

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

And here's input+output, first entering "1", then entering "0":

1
input: 1
0
input: 0
done

while (!(scan.nextInt() <= 0)) { takes an int and then input = scan.nextInt(); takes another one. You need to change the while loop to use input .

modified based on your code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM