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?
while (!(scan.nextInt() <= 0)) {, what do you expect that to do? Where it saysinput = scan.nextInt();, what do you expect that to do? Between those two lines of code, how many times do you see the codescan.nextInt()? When you run the code, how many times do you have to type the number? Do you see a correlation?scan.nextInt()in thewhilestatement, so that runs first, and then if the rest of the condition is true (so, if!(scan.nextInt() <= 0)returns "true") the next line is one morescan.nextInt(). Each pass through the loop, the same thing will happen – thewhilecondition, then one more inside the loop.