次のプログラムを検討してください。
import java.util.Scanner;
public class StreetPeople {
private static Scanner keyboard = new Scanner(System.in);
public static void main(String [] args) {
int houses;
int houseNumbers[];
int count;
int houseAges[][] = new int[4][];
int age;
int people;
System.out.print("How many houses on the street? : ");
houses = keyboard.nextInt();
houseNumbers = new int[houses];
for (count = 0; count < houses; count++) {
System.out.print("What is the next house number? : ");
houseNumbers[count] = keyboard.nextInt();
}
for (count = 0; count < houseNumbers.length; count++) {
System.out.print("How many people live in number " + houseNumbers[count] + ": ");
people = keyboard.nextInt();
houseAges[count] = new int[people];
for (int i = 0; i < houseAges.length; i++) {
System.out.print("What is the age of person " + (i+1) + ":");
age = keyboard.nextInt();
houseAges = new int[people][age];
}
}
}
}
コンソール ウィンドウの出力は次のとおりです (これは StackOverflow によって要約されたと思います)。
How many houses on the street? : 4
What is the next house number? : 1
What is the next house number? : 3
What is the next house number? : 4
What is the next house number? : 6
How many people live in number 1: 5
What is the age of person 1: 32
What is the age of person 2: 28
What is the age of person 3: 12
What is the age of person 4: 8
What is the age of person 5: 5
How many people live in number 3: 1
What is the age of person 1: 84
How many people live in number 4: 5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at StreetPeople.main(StreetPeople.java:31)
コードはそこまで完全に正常に動作します。なぜ何度か繰り返してもうまくいくのか、私は完全に途方に暮れていますが、家番号4ではうまくいきません。