+ 1

Please check the code

Hello everyone! I've written array sum code in eclipse and it's working perfectly. There I have one package and the .java files. I've tried to write this code in sololearn website and I'm getting one error. What's the problem? ..\Playground\:14: error: non-static method sum(int[]) cannot be referenced from a static context System.out.println(test.sum(arr)); import java.util.Scanner; public interface Arrsum { public int sum (int [] arr); } public class test implements Arrsum { @Override public int sum (int [] arr) { int z = 0; for (int i = 0; i < arr.length; i++) { z += arr[i]; } return z; } } public class Program { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int [] arr = new int [5]; for (int i = 0; i < arr.length; i++) { arr[i] = scn.nextInt(); } test ts = new test(); System.out.println(test.sum(arr)); } }

27th Oct 2016, 9:27 PM
Dima Simonishvili
Dima Simonishvili - avatar
4 odpowiedzi
+ 6
I think the problem if that you are trying to call the sum method of the test class as it were a static method (a class' method) when is not defined that way in your code. You should call the function from an instantiated test class object, like ts. Try changing this line (the one causing the error): System.out.println(test.sum(arr)); with this one: System.out.println(ts.sum(arr)); Hope it works!
28th Oct 2016, 12:02 AM
Nelson Urbina
Nelson Urbina - avatar
+ 4
@Dima You are welcome.. and don't worry.. it happens to all of us... all the time... that's why is better not to program alone... specially when learning... you don't get stuck too long when your brain stops working properly ;-) Learning to program together with a friend or in a community like this is great to keep you going.
28th Oct 2016, 10:39 AM
Nelson Urbina
Nelson Urbina - avatar
+ 1
@Nelson you are right, I should call ts not test. Now I realized it. It was late night and my brain wasn't working properly. Thanks for helping!
28th Oct 2016, 8:19 AM
Dima Simonishvili
Dima Simonishvili - avatar
+ 1
@Nelson Yes, it's awesome 😄
28th Oct 2016, 1:49 PM
Dima Simonishvili
Dima Simonishvili - avatar