0

I want to write a program that keeps track of how many times a bus is late.

So the user is asked to enter an int value, indicating how many minutes late.

Once a negative int is entered, the program should stop.

What I’m having trouble with is making the program repeat only for inputs of 0 or more.

The program repeats regardless of what int is inputted.

I did something like below:

import java.util.Scanner;

public class LateBus {

    public static void main(String[] args) {
        int enter_minutes = enterMinutes();
        loop(enter_minutes);
    }

    public static int enterMinutes() {
        Scanner enter = new Scanner(System.in);
        System.out.print("How many minutes late was the bus? ");

        int late = enter.nextInt();
        return late;
    }

    public static void loop(int a) {
        while (a >= 0) {
            enterMinutes();
        }
    }

}

2 Answers 2

2

Let's look at this function:

public static void loop(int a) {
    while (a >= 0) {
        enterMinutes();
    }
}

The value of a never changes. a >= 0 will always be true or never be true depending on the initial value for a. Since a is used internally to this function, you should not pass it in as a parameter. And you should be sure to change it:

public static void loop() {
    int a = enterMinutes();
    while (a >= 0) {
        a = enterMinutes();
    }
}

Now you call the function like this:

public static void main(String[] args) {
    loop();
}

Note:

Everyone makes logic mistakes in their code as they write it. To find them, you need to learn how to debug. I suggest that you read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ for some tips on how to debug your code so that you can find these kinds of problems on your own.

Sign up to request clarification or add additional context in comments.

Comments

0

The while loop will stop when a is negative, but you do not change its value.
Do it like this

while (a >= 0) {
    a = enterMinutes();
}

now the value changes to what the user inputs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.