Gojira
Gojira

Reputation: 67

This do-while loop is not working, I can't understand why

So I'm trying to make a program where the user enters the age of its students until it enters -1. After -1, the program has to calculate the number of students and average age. I can't get out of the do-while loop, for some reason. What a headache! Anyway, here's the code

Thanks in advance.

    public static void main(String[] args) {
    // Input
    Scanner input = new Scanner(System.in);

    // Variables
    int escapeNumber = 0;
    int[] studentsAge = new int[50];

    do {
        // Input
        System.out.println("Student's age (Type -1 to end): ");

        // Set escapeNumber to what the user entered to break the while loop
        escapeNumber = input.nextInt();

        // Populate the array with the ages (Cannot be a negative number)
        if (escapeNumber > 0) {

            for (int arrayPos = 0; arrayPos < studentsAge.length; arrayPos++) {
                studentsAge[arrayPos] = input.nextInt();
            }
        }

    } while (escapeNumber != -1);

    // When -1 is entered, the program goes here and makes the following
    // TODO: Number of students and average age

}

Upvotes: 3

Views: 95

Answers (1)

Eran
Eran

Reputation: 393946

You have two loops, and you only test for -1 in the outer loop. The inner for loop doesn't test for -1 input.

It would make more sense to eliminate the for loop :

int arrayPos = 0;
do {
    // Input
    System.out.println("Student's age (Type -1 to end): ");

    // Set escapeNumber to what the user entered to break the while loop
    escapeNumber = input.nextInt();

    // Populate the array with the ages (Cannot be a negative number)
    if (escapeNumber > 0 && arrayPos < studentsAge.length) {
         studentsAge[arrayPos] = escapeNumber;
         arrayPos++
    }

} while (escapeNumber != -1 && arrayPos < studentsAge.length);

I added another condition to exit the loop - when the array is full.

Upvotes: 6

Related Questions