为了账号安全,请及时绑定邮箱和手机立即绑定

我收到我认为是数组语法错误的信息,不知道要修复什么

我收到我认为是数组语法错误的信息,不知道要修复什么

拉风的咖菲猫 2023-05-17 14:43:27
必须创建一个使用 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。


查看完整回答
反对 回复 2023-05-17
  • 1 回答
  • 0 关注
  • 83 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信