+ 1

why it gives me error?

public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=1; x<=myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } }

29th Oct 2016, 6:53 PM
Robert Moisa
Robert Moisa - avatar
5 odpowiedzi
+ 3
Because you are trying to access invalid element arrays first element is 0 exp: int[] arr={1,2,3};//length =3; arr[0]=1; arr[1]=2; arr[2]=3; correct like this ... for(int x=0;x<arr.lenght;x++) ...
29th Oct 2016, 7:01 PM
bayram akdemir
bayram akdemir - avatar
+ 1
your problem is with sum += myArr try changing it
29th Oct 2016, 7:08 PM
imaqtpie
imaqtpie - avatar
0
I did it wrong because I didn't look at the index. ty😁
29th Oct 2016, 7:05 PM
Robert Moisa
Robert Moisa - avatar
0
look at your code in for(int x=1; x<=myArr.length; x++) the index of array start from 0 so you have to make for like this for(int x=0; x<=myArr.length; x++) now here is an other problem the array end with index (arraylength-1) so you here in code when x= myArr.length will access myArr[x] which means myArr[myArr.length ] which does not exist so you have to make the code like this for(int x=0; x<myArr.length; x++) or like this for(int x=0; x<=myArr.length-1; x++)
29th Oct 2016, 9:38 PM
Ahmed Helal Ahmed
Ahmed Helal Ahmed - avatar
0
hi
16th Dec 2016, 10:17 AM
Praveen Kairasi
Praveen Kairasi - avatar