Using methods from another class in the main?

2019-03-01 01:57发布

问题:

Okay so I did search this question and a decent amount of results showed up. All of them seemed to have pretty different scenarios though and the solutions were different for each one so I'm a bit confused.

Basically, I have a Driver class that runs my program and contains the main method. I have a second class that has a few methods for editing a party (like party of characters in a game). What I wanted to do was this (part of main method)

System.out.println("Are you <ready> for your next battle? Or do you want to <edit> your party?");
Scanner readyScanner = new Scanner(System.in);
String readyString = readyScanner.next();
while(!readyString.equals("ready") && !readyString.equals("edit")) {
    System.out.println("Error: Please input <ready> if you are ready for your next battle, or <edit> to change your party.");
    readyScanner = new Scanner(System.in);
    readyString = readyScanner.next();
}
if(readyString.equals("edit")) {
    displayEditParty(playerParty, tempEnemy);
}

A lot of this is just some background code, the problem lies with

displayEditParty(playerParty, tempEnemy);

I get the error

Driver.java:283: cannot find symbol
symbol  : method  
displayEditParty(java.util.ArrayList<Character>,java.util.ArrayList<Character>)
location: class Driver
displayEditParty(playerParty, tempEnemy);

So, how could I call this method from another class in my main? In my code I use methods from other classes a few times, I'm a bit confused as to this one doesn't work.

回答1:

You should make displayEditParty function public static and then you can use it in other class by className.displayEditParty(?,?);

Methods of class can be accessible by that class's object only. Check below code:

class A{

    void methodA(){
        //Some logic
    }

    public static void methodB(){
        //Some logic
    }
}

public static void main(String args[]){

    A obj = new A();
    obj.methodA(); // You can use methodA using Object only.

    A.methodB();  // Whereas static method can be accessed by object as well as 
    obj.methodB(); // class name.
}


回答2:

If your method is a static, you can call ClassName.methodName(arguments);

If your driver class not a static one you should create an instant of that class and call your method.

ClassName className=new ClassName();
className.displayEditParty(playerParty, tempEnemy);


回答3:

I dont see where your declaring the Driver class in your code.

Driver foo = new Driver();
foo.displayEditParty(playerParty, tempEnemy);


标签: java class