Non-static reference to static in Java (but I'm only using static)

159 views Asked by At

I'm getting the following errors when this code runs: Error: Cannot make a static reference to the non-static field c Error: Cannot make a static reference to the non-static field d This happens 11 times total with the code:

import java.util.Scanner;
class problemStatement
{
  int c = 0, d = 0;
  public static void main(String [] args)
  {
    Scanner in = new Scanner(System.in);
    System.out.println("Please enters two integers - 0 0 to end program");
    do
    {
      c = in.nextInt();
      d = in.nextInt();
      System.out.print("User input: " + c + " " + d + " " + displayValues);
      if (isFinished(c,d))
      {
        System.out.println("End of Program.");
      }
      else
      {
        displayValues (c,d);
      }
    }while(!isFinished(c,d));
  }
  public static int min ( int a, int b)
  {
    if ( a >=b)
    {
      return b;
    }
    else
    {
      return a;
    }
  }
  public static int max ( int a, int b)
  {
    if ( a >=b)
    {
      return a;
    }
    else
    {
      return b;
    }
  }
  public static boolean isFinished ( int a, int b )
  {
    if (a==0&&b==0)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
    public static void displayValues ( int a, int b )
    {
      int e = min(a,b);
      int f = max(a,b);
      System.out.print("Max value: " + e + " Min value: " + f);
    }
  }

I agree some of the code is redundant, however, I'm a newbie and this is to so I can learn more about Java. Any help is appreciated.

2

There are 2 answers

1
Christopher Helck On BEST ANSWER

Simon is correct. Another approach is to define c and d inside of main. Something like

  int c = in.nextInt();
  int d = in.nextInt();

This gives better scoping.

5
Simon Zambrovski On

Your variables c and d are instance variables (non-static). In order to access them, you need to have an instance of problemStatement class. So either you make them static or you create an instance = new problemStatement() and access them by instance.c and instance.d.

In your case I would make everything static.