2013-10-08 28 views
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]; 

     } 

    } 





    } 

}  

这里迭代是控制台窗口输出(我的猜测得到了由堆栈溢出冷凝):我的代码有什么问题?通过二维数组

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

+0

解释什么是预期行为以及为什么它看起来不正确。 – logoff

+0

我预计它会创建一个大小为x的不规则数组,表示该房屋中有多少人居住,该数组中的每个元素将具有房屋中每个人的年龄。 – NickP

回答

1

houseAges只有4行。

int houseAges[][] = new int[4][]; 
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]; 
+0

ahhh非常感谢 – NickP

+0

我将它改为你发布的内容,但它仍然无效。该错误似乎在:houseAges [count] = new int [people]; – NickP

+0

@NickD从您的代码中删除下面的行houseAges [count] = new int [people]; – Prabhakaran

1

这里删除以下行,固定大小。当你拨打下一个号码并出现错误时。

int houseAges[][] = new int[4][]; 
1

这是你的问题:

houseAges = new int[people][age]; 

您重新初始化houseAges阵列完全

现在既然在你的第三宫,你选择了1个人,那么你与一个人这使得初始化数组第二个索引上的循环崩溃(从现在开始houseAges第一维的大小为1)

+0

非常感谢你 – NickP

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 in every iteration 

    }