0

So, I'm trying to make an extremely simple program.

public class test {
    public static void main (String args[]){
        System.out.println("Yum! Pi!");
        int pi = 1;
        varCreate();
        varAdd();
    }
    public void varCreate () {
        pi++;
    }
    public void varAdd () {
        System.out.println(pi);
    }
}

It's wont let me do this, it says something along the lines of: "cannot make static reference to the non-static method varAdd from the type test" I'm sure there's an extremely simple error, I just can't find it. Kudos for any help!

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
Cowthulhu
  • 528
  • 2
  • 8
  • 21

2 Answers2

4

static methods can only call static methods.

Either make the functions static or create an instance variable to call the methods.

public class test {
    static int pi = 1;
    public static void main (String args[]){
        System.out.println("Yum! Pi!");
        varCreate();
        varAdd();
    }
    public static void varCreate () {
        pi++;
    }
    public static void varAdd () {
        System.out.println(pi);
    }
}
P.P
  • 117,907
  • 20
  • 175
  • 238
3

You need to instantiate your Test class to use (non-static) methods:

class Test {
    int pi = 1;

    public static void main (String args[]){
        System.out.println("Yum! Pi!");
        Test t = new Test();
        t.varCreate();
        t.varAdd();
    }
    public void varCreate () {
        pi++;
    }
    public void varAdd () {
        System.out.println(pi);
    }
}

`

Usman Salihin
  • 291
  • 1
  • 8