Search code examples
javajava.util.scanner

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?


Solution

  • 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