-2

I've just started Java this semester and I'm very new to it. I'm struggling to get an array method to print out anything through my main method. The example given below is from the notes, except for the info in the main method which I added, but I cannot get it to print anything through the main method since it gives me an error every time I try to compile it.

This is the array method example that was given:

import java.util.*;

import java.text.*; public class ArrayDemo {

private static Random rng = new Random();  
private static DecimalFormat format =new DecimalFormat();
static{
    format.setMaximumFractionDigits(4); 
}

public static void main(String [] args){


    int num1 = 5; 
    arrayDemo(num1);

}



public void arrayDemo(int n){

    double [] a = new double[n]; 
    double [] c = {42, -99.9999, rng.nextGaussian() * 50};

    for (int i = 0; i < a.length; i++){ 
        a [i] = rng.nextDouble(); 
    }

    double sum = 0;
    for (int i =0; i< a.length; i++){

        sum += a[i];  
    }

    System.out.println("The values add up to" + format.format(sum));
    System.out.println("The elements are:" + Arrays.toString(a));
}







}

The error that I keep getting is "non static method arrayDemo(int n) cannot be referenced from a static context.".

I've searched up many tutorials on arrays but I still cannot figure out why I keep getting this error. Any help will be greatly appreciated.

snk
  • 91
  • 1
  • 8

2 Answers2

0

The Main-Method is an static method, so make your method static and you can call it..

public static void arrayDemo(int n){

 ...

}
Hubi
  • 440
  • 1
  • 11
  • 25
0

You cannot call a non-static method from a static method. Since main is a static method, it cannot use the non-static arrayDemo method.

The reason main is static is because static methods can be called without creating an object of the class, this is important since main is the entry-point of your program.

rhowell
  • 1,165
  • 8
  • 21