そこで、ユーザーが-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
}
2つのループがあり、外側のループで-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);
ループを終了するための別の条件を追加しました-配列がいっぱいになったとき。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加