所以我正在尝试制作一个用户输入学生年龄的程序,直到输入-1。在-1之后,程序必须计算学生人数和平均年龄。 出于某种原因,我无法摆脱do-while循环。太头疼了! 无论如何,这是代码
提前致谢。
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
}
答案 0 :(得分:6)
你有两个循环,你只在外循环中测试-1。内部for循环不测试-1输入。
消除for循环会更有意义:
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);
我添加了另一个退出循环的条件 - 当数组已满时。