-2

My code isn't compiling the error that is given to me is "non-static method sumArray(double[]) cannot be referenced from a static context". I have tried to figure this out but I'm not sure what I need to change. Please help and let me know what the error is.

import java.util.*; public class Homework5 {

public static void main( String[] args )
{

    Scanner key = new Scanner(System.in);
    System.out.println("How many numbers would you like in the array?");
    int arrayLength = key.nextInt();

    Homework5 inst1 = new Homework5();

    double[] numbers = new double[arrayLength];
    System.out.println("Enter " + arrayLength + " numbers:");

    for( int i=0; i < arrayLength; i++ )
    {
        numbers[i] = key.nextDouble();
    }
    System.out.println( "The sum is "+sumArray(numbers));
}

public double sumArray( double[] newArray )
{
    double total=0;

    for( int index = 0; index < newArray.length ; index++ )
    {
        total = total+newArray[index];
    }

    return total;  
}

}

Riley
  • 67
  • 5

2 Answers2

0

change your method to static:

public static double sumArray( double[] newArray ) {
    ...
}

Explanation: main is static, but you did not declare sumArray as static. In Java, every non-static method needs an instance which is passed as this to the method.

Axel
  • 13,939
  • 5
  • 50
  • 79
0

sumArray method needs to be a static one.

sitakant
  • 1,766
  • 2
  • 18
  • 38