i dont know why this exception happens...
here's my code
public int add(int ... values) {
int sum = 0;
for(int i : values) {
sum = values[i];
}
return sum;
}
and in main method i use add()...
public static void main(String[] args){
Calulator myCal = new Calculator();
int result = myCal.add(5,5,5,5,5,5,5);
System.out.println(result);
}
CodePudding user response:
for(int i : values) {
sum = values[i];
}
this code makes no sense at all. i doesn't represent the index you iterate over, but the value.
Change your code to:
for(int i : values) {
sum = i;
}
EDIT: though, since your array should hold enough elements: I don't understand why you get that exception, if this is really the input you provide.
CodePudding user response:
The code you provided does not produce the ArrayIndexOutOfBoundsException. However, I think you use the for-each loop incorrectly. Under some condition the exception may throws.
The i
in the for-each loop holds the element of the array, not the index. You take the value and use it as an index and further retrieve a value from the array. If the array length is shorter then the value holding in i
, ArrayIndexOutOfBoundsException occurs. I modified your add()
.
public int add(int... values) {
int sum = 0;
for (int i : values) {
sum = i;
}
return sum;
}
This is the main
public static void main(String[] args) {
Calculator myCal = new Calculator();
int result = myCal.add(0, 1, 1, 2, 3, 5, 8); // result = 20
System.out.println(result);
}
CodePudding user response:
The Exception is caused because the value at 0th index is assigned to i,and if i is greater than the length of the array it throws the exception. It is not necessary that 0th index value is greater than the length it could be any element in the array.