我的数组超出范围,但它的设置高于 im 从它调用的值


public class hw16 {
   
    public static void main(String[] args) {
        MonthlyRecord MonthRecord = new MonthlyRecord("January", 31);
        MonthRecord.Transaction(5, 600);
    
    }
    
}
    
public class MonthlyRecord {
    private String month;
    private int day;
    private double[] moneyDaily = new double[day];
    public MonthlyRecord() {
        this.month = "January";
        this.day = 0;
        this.moneyDaily[1] = 0;
    }
    public MonthlyRecord(String name, int day) {
       
        System.out.println("Hello");
        this.setMonthlyRecord(name);
        this.setDays(day);
    }
    public void setDays(int temp) {
        this.day = temp;
    }
    public void setMonthlyRecord(String temp) {
        this.month = temp;
    }
    public int setDays() {
        return this.day;
    }
    public String getMonthlyRecord() {
        return this.month;
    }
    public void Transaction(int daynum, int amount) {
        System.out.println("You've made $" + amount + " on the " + daynum + "th day");
        System.out.println(moneyDaily[daynum]);
    }
}

我收到错误:

您好,您在第 600 天赚了 5 美元 线程"main"中的异常java.lang.ArrayIndexOutOfBoundsException: 5 athwk16jzuramski1.MonthlyRecord.Transaction(MonthlyRecord.java:40( athwk16jzuramski1.Hwk16jzuramski1.main(Hwk16jzuramski1.java:11( Java结果:1

所以它说我的数组超出了我不明白的范围?如果我将 day 设置为数组的长度,为什么当数组长度应该是 31 时,它说它在 int 5 时越界?

我认为

正在发生的事情是,在类的顶部,您正在构造函数之外monthDaily[]实例化数组。由于 int 变量day仅在构造函数中初始化,因此您还应该在构造函数中实例化monthDaily[]变量。因此,代码的开头部分如下所示:

public class MonthlyRecord {
    private String month;
    private int day;
    private double[] moneyDaily;
    public MonthlyRecord() {
        this.month = "January";
        this.day = 0;
        this.moneyDaily = new double[1]; //variable is instantiated to have one slot as default
    }
    public MonthlyRecord(String name, int day) {
        System.out.println("Hello");
        this.setMonthlyRecord(name);
        this.setDays(day);
        moneyDaily = new double[days]; //array gets instantiated with number of slots equal to the value of the day variable
    }

您需要在调用构造函数时设置数组的大小:

public MonthlyRecord(String name, int day) {
    moneyDaily = new double[day];
    System.out.println("Hello");
    this.setMonthlyRecord(name);
    this.setDays(day);
}

否则,数组moneyDaily的大小将与最初当天的大小相同,即 0。

相关内容

最新更新