如何从另一个类调用方法

时间:2017-03-17 16:27:14

标签: java methods

您好我是面向对象编程的新手。通常我会使用构造函数调用方法。但在这种情况下它似乎不起作用。 我想从CommandWords类调用方法getCommands()到Game类。有谁可以帮我理解我是如何做到这一点的?感谢

public class Game() {
    private void printHelp() 
    {
    System.out.println("You are " + currentRoom.getDescription());
    System.out.println();
    System.out.println("Your command words are:");
    System.out.println("   go quit help");
    //getCommands();
    System.out.println();
    System.out.print("Your exits are: ");
    if(currentRoom.northExit != null) {
        System.out.print("north ");
    }
    if(currentRoom.eastExit != null) {
        System.out.print("east ");
    }
    if(currentRoom.southExit != null) {
        System.out.print("south ");
    }
    if(currentRoom.westExit != null) {
        System.out.print("west ");
    }
    System.out.println();
    }
}

我想从中调用方法getCommands()

的类
public class CommandWords
{
// a constant array that holds all valid command words
private static final String[] validCommands = {
    "go", "quit", "help"
};

//Method which gets the String representation of valid commands
public String getCommands() {
    String printer= "";
    for (int i=0; i<validCommands.length; i++) {
        printer = printer + validCommands[i] + ", ";
    }
    return printer;
}

/**
 * Constructor - initialise the command words.
 */
public CommandWords()
{
    // nothing to do at the moment...
}

}

4 个答案:

答案 0 :(得分:0)

你不会打电话给方法&#34;与构造函数。您需要创建CommandWords类的实例,然后在其上调用方法:

public class Game() {
    private void printHelp() 
    {
    System.out.println("You are " + currentRoom.getDescription());
    System.out.println();
    System.out.println("Your command words are:");
    System.out.println("   go quit help");
    CommandWords words = new CommandWords();
    String results = words.getCommands();

您是否阅读过Java Tutorials

答案 1 :(得分:0)

---
-------
System.out.println("Your command words are:");
System.out.println("   go quit help");
CommandWords commandWords = new CommandWords();
String s1 =commandWords.getCommands();
System.out.println();
System.out.print("Your exits are: ");
-------
---

答案 2 :(得分:0)

您可以通过该实例创建新的对象实例和调用方法。

CommandWords commandWords = new CommandWords();
String commands = commandWords.getCommands();
System.out.println(commands);

将上一行替换为 // getCommands();

答案 3 :(得分:0)

无需对构造函数执行任何操作。只需创建一个CommandWords类的实例并调用getcommands方法。

private void printHelp() 
{
System.out.println("You are " + currentRoom.getDescription());
System.out.println();
System.out.println("Your command words are:");
System.out.println("   go quit help");
CommandWords command_words=new CommandWords();
command_words.getCommands();
System.out.println();