문제

CollegeTester.java:10: error: non-static method getCommand() cannot be referenced from a static context
        getCommand();//goes to command
    ^

How would I enter this method. Making it public static void only causes more problems

import java.util.Scanner;

public class CollegeTester
{   
    public String name;
    Scanner input = new Scanner(System.in);

    public static void main(String[] args)
    {
        getCommand();//goes to command
    }

    //Ask user for a command
    public void getCommand()
    {
        // do stuff
    }
}
도움이 되었습니까?

해결책

You can call it as in main :

CollegeTester c = new CollegeTester();
c.getCommand();

다른 팁

Non-static methods are instance methods, and thus accessed over an instance of the class:

new CollegeTest().getCommand();

Create an instance of the CollegeTester class in main method and call the method.

new CollegeTester().getCommand();

You need to create an instance of CollegeTester :

   main(...)
   {
      CollegeTester t = new CollegeTester();
      t.getCommand();
   }

getCommand() is not static so you can not call this in main() as main() is static.You have create an object and then call getCommand().

Or make getCommand() static

This is the way by creating object and calling getCommand()

    import java.util.Scanner;

    public class CollegeTester
    {   
    public String name;
    Scanner input = new Scanner(System.in);

    public static void main(String[] args)
    {
CollegeTester c=new CollegeTester();
        c.getCommand();//goes to command
    }

    //Ask user for a command
    public void getCommand()
    {
        do stuff
    }

This is the way of making getCommand() static

import java.util.Scanner;

public class CollegeTester
{   
public String name;
Scanner input = new Scanner(System.in);

public static void main(String[] args)
{
    getCommand();//goes to command
}

//Ask user for a command
public static void getCommand()
{
    do stuff
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top