-6

Every time I try to compile my program I get this error "nonstatic method primeNum(int) cannot be referenced from a static context".

In this program, I have to write a method that determines if a number is prime and use this method in an application that determines all the prime numbers between 1 and 100.

Here is my code:

import java.io.*;
import java.util.Scanner;
public class Program7

{
public static void main (String args[])
{
Scanner scanner = new Scanner(System.in);

int x, r=0, prime;
int num[]= new int[100];

while (r<100){
  prime=primeNum(x);
  System.out.println(prime);
  r++;
  }
}

public int primeNum (int x){

for(i=1; i<=x; i++){
  if(x%i==0)
  count++;
  return x;
  }
  if(count==2)
  System.out.println();
  }
}
Jason C
  • 38,729
  • 14
  • 126
  • 182
airgold
  • 1
  • 2
  • 6
  • 2
    In your rush to post your problem, you neglected to look into all the Related questions and answers. Turn your head towards the right of your screen. – Sotirios Delimanolis Apr 11 '14 at 03:22
  • @SotiriosDelimanolis He did not ask a question. – Dave L. Apr 11 '14 at 03:23
  • Also, the error means exactly what it says. `main` is `static`, and you are trying to call the non-static method `primeNum` from there. See also [understanding class methods](http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html) from the official tutorial. It is concise and well-written and will give you the information you need here. – Jason C Apr 11 '14 at 03:24
  • I believe this is programming 101 and applies to all OOP programming languages. Think of it this way. Program7 is self-contained with main method which is static; therefore all methods referenced within this class will have to be static if they are to be used in main. I am pretty sure Classes follow the same concept. System.out.println() – yardpenalty.com Apr 11 '14 at 03:40

1 Answers1

0

Yes, you cannot call a non-static method from a static context. You have two options:

Declare primeNum () static:

static int primeNum (int x){

Create an instance of primeNum and call primeNum () via that reference:

PrimeNumClass primeNumObj = new PrimeNumClass();
int returnVal = primeNumObj.primeNum(x);
ngrashia
  • 9,869
  • 5
  • 43
  • 58