This do-while loop doesn't work, I can't figure out why
So I am trying to create a program where the user enters the age of their students until -1 is entered. After -1, the program should calculate the number of students and the average age. For some reason, I cannot get out of the do-while loop. 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 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
}
+3
source to share
1 answer
You have two loops and you only check -1 in the outer loop. The inner for loop does not check input -1.
It would be wiser to eliminate the for loop:
int arrayPos = 0;
do {
// Input
System.out.println("Student 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 one more condition to exit the loop - when the array is full.
+6
source to share