0

I'm trying to create a function sum then call it in main, but I'm getting compile-time error, and I don't understand why this is incorrect.

class FindSum {
    int sum(int[] arr) {
        int sum = 0; // O(1)
        for (int i = 0; i < arr.length; i++) { // n times
             sum += arr[i]; // O(1)
        }
        return sum; // O(1)
    }

    // Driver program to test above functions
    public static void main(String[] args) {
        int arr[] = new int[]{5, 5, 10, 100, 10, 5};
        System.out.println(sum(arr));
    }
}
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
qazwsx123
  • 9
  • 1
  • 2
  • Would be *really helpful* if you could actually tell us what the error is. Questions asking us for debugging help are explicitly off topic. Please provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that demonstrates the error, expected and actual behavior. – Andrew Li Oct 04 '16 at 03:15
  • You should probably include what the compiler error SAYS, which is the most important part of a compiler error. – nhouser9 Oct 04 '16 at 03:15
  • You need to make the method `sum` static. @AndrewL. this is a bad question but it is also a MCVE... its complete, reproduces the problem, and is minimal. – nhouser9 Oct 04 '16 at 03:16
  • @nhouser9 Your right, but I'd like to stress the part where I ask to demonstrate the error, as in telling us what us what it actually is. – Andrew Li Oct 04 '16 at 03:18
  • The OP, @qazwsx123, should get an IDE (like eclipse, its FREE). It makes it a lot easier to find compile time errors as well as run time ones, and in general makes your life a lot easier. If (s)he already has one, then they need to learn how to use it better. – MercyBeaucou Oct 04 '16 at 03:20
  • While the question you asked is a duplicate, in Java 8+ you could write `System.out.println(IntStream.of(new int[]{5, 5, 10, 100, 10, 5}).sum());` – Elliott Frisch Oct 04 '16 at 03:22

2 Answers2

2

You are calling a non-static method from a static method. You can either change sum to be static like this:

    public static int sum(int[] arr) {

or instantiate a new object in the main function:

public int sum(int[] arr) {
    int sum = 0; // O(1)
    for (int i = 0; i < arr.length; i++) { // n times
         sum += arr[i]; // O(1)
    }
    return sum; // O(1)
}

// Driver program to test above functions
public static void main(String[] args) {
    int arr[] = new int[]{5, 5, 10, 100, 10, 5};
    FindSum instance = new FindSum();
    System.out.println(instance.sum(arr));
}
deathyr
  • 433
  • 2
  • 11
1

method sum has to be static in order to be called in the main method.

deviantxdes
  • 469
  • 5
  • 17