必須創建一個使用 SuperHero 類的程序,該類使用名稱類和日期類。在主代碼中,將屬性分配給英雄對象時收到錯誤。public class JavaProgram{ public static void main (String [] args){ Date [] birthDay = new Date [3]; Name [] name = new Name [3]; SuperHero [] hero = new SuperHero [3]; for (int i = 0; i < hero.length; i++){ birthDay[i] = new Date(); name[i] = new Name(); hero[i] = new SuperHero(); } birthDay[1].setDate(10,10,87); birthDay[2].setDate(5,10,99); birthDay[3].setDate(3,12,79); name[1].setName("Michael"); name[2].setName("Scott"); name[3].setName("Jim"); SuperHero hero [1] = new SuperHero(name[1], "Suit", "Cape", "Flying", birthDay[1] ); SuperHero hero [2] = new SuperHero(name[2], "Suit", "No Cape", "Flying", birthDay[2] ); SuperHero hero [3] = new SuperHero(name[3], "Suit", "Cape", "Flying", birthDay[3] ); }} private Name name; private String suit; private String cape; private Date birthDay; private String power; public SuperHero(Name name, String suit, String cape, String Power,Date birthDay){ this.name = name; this.suit = suit; this.cape = cape; this.power = power; this.birthDay = birthDay; } public Date getBirthDay(){ return this.birthDay; } public Name getName(){ return this.name; } public void setSuit (String b){ suit = b; } public String getSuit(){ return suit; } public void setCape (String t){ cape = t; } public String getCape(){ return cape; } public void setPower(String v){ power = v; } public String getPower(){ return power; }}
1 回答

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
這里有兩件事是錯誤的/有問題的:
1:您沒有正確訪問英雄數組。訪問 hero 數組的第 n 個元素是這樣完成的:
hero[n]
要為您需要的英雄數組中的第 n 個位置分配一個值
hero[n] = new SuperHero( ... )
2:在 Java 中,數組是從 0 開始索引的。這意味著大小為 3 的數組具有索引 0、1 和 2 hero[3]
,并且name[3]
都將導致 IndexOutOfBoundsException。
添加回答
舉報
0/150
提交
取消