简体   繁体   中英

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

}

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.

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