2013-10-08 61 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 

    }