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 = new int[people][age];

houseAges完全重新初始化阵列

现在因为在你的第三所房子里你选择了 1 个人然后你用一个人初始化你的数组,这使得循环在第二个索引上崩溃(因为现在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 回答
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 回答