必须创建一个使用 SuperHero 类的程序,该类使用 Name 类和 Date 类。在主代码中,为英雄对象分配属性时收到错误。
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;
}
}
public class Date
{
private int month;
private int day;
private int year;
public Date() { month = 0; day = 0; year = 0; }
public void setDate( int m, int d, int y )
{
month = m; day = d; year = y;
}
public String getDateString()
{
return month + "/" + day + "/" + year;
}
}
public class Name{
private String name;
public void setName (String n){
name = n;
}
public String getName(){
return name;
}
}
当我尝试编译主代码时出现此错误:
JavaProgram.java:20: error: ']' expected
SuperHero hero [1] = new SuperHero(name[1], "Suit", "Cape", "Flying", birthDay[1] );
^
JavaProgram.java:21: error: ']' expected
SuperHero hero [2] = new SuperHero(name[2], "Suit", "No Cape", "Flying", birthDay[2] );
^
JavaProgram.java:22: error: ']' expected
SuperHero hero [3] = new SuperHero(name[3], "Suit", "Cape", "Flying", birthDay[3] );
^
3 errors
最佳答案
这里有两件事是错误/有问题的:
1:您没有正确访问英雄数组。访问英雄数组的第 n 个元素如下:
hero[n]
为您需要的英雄数组中的第 n 个位置分配一个值
hero[n] = new SuperHero( ... )
2:在 Java 中,数组是从 0 索引的。这意味着大小为 3 的数组的索引为 0、1 和 2 hero[3]
和 name[3]
都会导致 IndexOutOfBoundsException。
关于java - 我收到了我认为是数组的语法错误,不知道它想要修复什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57370299/