使用另一个类的方法在主? [英] Using methods from another class in the main?

查看:165
本文介绍了使用另一个类的方法在主?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我没有搜索这个问题,一个体面的结果出现了。所有的人似乎有不同的情况,但解决方案是不同的每一个,所以我有点困惑。

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.

基本上,我有一个Driver类,它运行我的程序并包含main方法。我有一个第二类,有几个方法编辑一方(如游戏中的字符的党)。我想做的是这个(主要方法的一部分)

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);

我收到错误

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.

推荐答案

你应该使 displayEditParty 函数public static然后你可以使用它在其他类中 className.displayEditParty(?,?); code>

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.
}

这篇关于使用另一个类的方法在主?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆