1

次のプログラムを検討してください。

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ではうまくいきません。

4

5 に答える 5

1

ここでは固定サイズ。次の番号にかけるとエラーになります。

int houseAges[][] = new int[4][]; 
于 2013-10-08T06:53:00.977 に答える
1

houseAges には 4 行しかありません。

int houseAges[][] = new int[4][]; 
于 2013-10-08T06:50:05.390 に答える
1

int houseAges[][] = new int[4][]; // ここに問題があります

以下のように変更を修正する

  System.out.print("How many houses on the street? : ");
  houses = keyboard.nextInt();
  houseNumbers= new int[houses];
  houseAges = new int[houses][];  //here you need to initialize houseAges 

コードから以下の行を削除します

 houseAges[count] = new int[people];
于 2013-10-08T06:50:10.607 に答える
1

これはあなたの問題です:

houseAges = new int[people][age];

houseAgesアレイを完全に再初期化します

3 番目の家で 1 人を選択したので、配列を 1 人で初期化すると、2 番目のインデックスでループがクラッシュします (houseAges最初の次元のサイズが 1 であるため)。

于 2013-10-08T06:54:48.050 に答える
1

問題は次のループにあります。

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];  // I guess it should be houseAges[people][i] = age; no need to reallocate the entire array on every iteration.
}
于 2013-10-08T06:56:09.673 に答える