+ 5
a task
Where is the error? public class Pj9 { public static void main(String[] args) { int [] a = {1,2,3,4}; System.out.println(sum); } public double arithmetic(int[] pj9) { int sum = 0; for (int i = 1; i < pj9.length; i++) { sum += pj9[i]; } return sum / pj9.length; } }
4 Antworten
+ 5
Have you tried running it in the Code Playground? It should say something about why it isn't working
You have println(sum) but there is no reference to 'sum' in the main method. 'sum' is defined in your 'arithmetic' method, so you need to call System.out.println(arithmetic(a)) to get the output I think you're looking for.
Also you will need to make the method static, because main is static and you haven't made an object using 'new'. Its a bit difficult to understand exactly why when you're first starting out, but when practising with this kind of setup make your methods static in the class you have the main method - until you learn some more ;)
+ 1
Thank you so much! Did As you said: created a new object, derived arithmetic (a). The result is 2.25. True the original idea was to get the result 2.5)))
+ 1
public class Pj9 {
public static void main(String[] args) {
int [] a = {1,2,3,4};
Pj9 sum = new Pj9();
System.out.println(arithmetic (a));
}
public static double arithmetic(int[] pj9) {
int sum = 0;
for (int i = 1; i < pj9.length; i++) {
sum += pj9[i];
}
return (double)sum / pj9.length;
}
}
0
int i = 0; ----> result 2.5