嗨,我是 Java 初学者,所以没有复杂的代码等
基本上,为了避免我的代码变得太长,我希望我的用户输入一个选择,然后我有一堆 for 和 elese 来说明如果他们输入某个短语会发生什么,例如
if(choice.equals("Fight")) {
//Grab code from fight.java/fight.class
}
else
{
if(choice.equals("Train")) {
//Grab code from train.java/train.class
}
else
对于另外两个可能的输入,依此类推。我只需要知道如何调用外部代码,这样它就不会变得太困惑。
最佳答案
您应该创建这些类的对象。
例如:
if(choice.equals("Fight")) {
//Grab code from fight.java/fight.class
fight f = new fight();
f.foo(); // A method
}else{
if(choice.equals("Train")) {
//Grab code from train.java/train.class
train t = new train();
t.foo(); // A method
}
//...
}
或者你可以尝试这样的静态方法:
public class train{
public static void foo(){
//...
}
}
然后就可以使用它了。
if(bool_expression){
train.foo(); // foo is a static method
}
关于java - 从其他类调用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18260001/