0
Summing array elements in Java
Someone please help me! When I write the same code (that is used to explain this part of arrays in the Java course) into code playground or Eclipse or any other IDE, it keeps telling me that there is an error! It says that the variable x in “sum+=myArr[x]” cannot be resolved to a variable. How come the code works in the lessons but does not anywehere else? Even in sololearn’s code playground...
5 Respuestas
0
Can you post the code?
0
int [ ] myArr = {6, 42, 3, 7};
int sum=0;
for(int x=0; x<myArr.length; x++) {
sum += myArr[x];
}
System.out.println(sum);
This is the code. It works well in the Java course when I try it in code playground but as soon as I copy it into another IDE or even into code playground in a new page it just writes error so I don’t understand the problem really.
0
This is because you have to put every code inside a class in Java... Try to put it in:
public class Test{
public static void main(String[] args){
// your code here...
}
}
On your local development environment, dont forget to name this file like class name (in this case Test.java)
0
Thanks! I’ll try it out. Hope it will work now.
0
I tried it out and it still doesn’t work... I put it in a class and gave it the same name as the file but still gives an error