简体   繁体   中英

Why am I getting ArrayIndexOutOfBoundsException?

So I got this assignment while my teacher is away, and basically I have to make a student project. The student has a name, marks, and average. To calculate the average I decided to store the marks inside a int[] array.

public void addQuiz(int m)
{
    int l = (marks.length);
    marks[l] = m;
}


int[] marks = new int[8];

But when I run the function:

student.addQuiz(90);

I get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8

Any help?

I'm not sure what the int[8] part does but it was in the tutorial I followed and it would give me a null pointer without it. There are eight marks in total so I just made it 8.

You can't dynamically add things to an array. You should use an array list instead.

Arraylist<Integer> marks = new ArrayList<Integer>();

then in your addQuiz method:

public void addQuiz(int m) {
    marks.add(m)
}

You'll probably also need to change your method for calculating the average a bit, but that should be trivial and I'll leave it to you.

The error says: ArrayIndexOutOfBoundsException: 8

You have an array with 8 elements, indexed from 0 to 7 (inclusive). This array has a length of 8, and you are actually trying to access marks[8], when you only can go up to 7.

In Java, Array index starts from '0'. so, you cannot access the index of the array equal to the length of the array.if your arrays length is '8', then the last index of the array is '7' not '8'. if you are trying to access the illegal index of the array, then ArrayIndexOutOfBoundException is thrown. the code should be changed to

public void addQuiz(int m)
{
    int l = (marks.length); //assuming marks is an array of length '8'
    marks[l-1] = m; //index is 7 now
}

To calculate the average, you need to sum up the contents of the array (provided all the values are of int values) and then divided by the lenght of the array

int sum = 0;
int avg = 0;
for(int i=0; i<array.length;i++){
sum =sum+array[i];
}
avg = sum/array.length;

Hope this gives an idea

使用Arraylist<Integer> ,然后可以动态添加到列表中

There is not index in this array for this marks[l] = m; . use marks[l-1] = m;

You can call this for loop in main for getting marks 8 times.

for(int i=0;i<8;i++)
student.addQuiz(<marks you want to enter>, i);

You can define addQuiz function like below

public void addQuiz(int m, int arrayIndex)
{
marks[arrayIndex] = m;
}

int[] marks = new int[8]; //this will be as it is

These are minimal changes. You can make your code better by passing array marks to addQuiz as a parameter. But this will also work, its just that this is not the best way to write code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM