My Array is out of bounds, but its set higher than the value im calling from it

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]);

    }

}

I’m getting an error:

Hello You’ve made $600 on the 5th day Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5 at hwk16jzuramski1.MonthlyRecord.Transaction(MonthlyRecord.java:40) at hwk16jzuramski1.Hwk16jzuramski1.main(Hwk16jzuramski1.java:11) Java Result: 1

SO it say’s my array is out of bounds which I don’t understand? If I’m setting day to the length of my array why is it saying its out of bounds at int 5 when the array length should be 31?

Answer

What I think is happening is that at the top of your class your are instantiating the array monthDaily[] outside of the constructor. Since the int variable day only gets initialized in the constructors you should also instantiate the monthDaily[] variable in the constructor. Hence the beginning part of your code would look like:

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
    }

Leave a Reply

Your email address will not be published. Required fields are marked *