如何将数组从main方法传递到java中的另一个方法?

时间:2012-03-10 17:56:05

标签: java

我的main方法中有一个Person数组,我必须将该数组传递给Game类中的PlayGame()方法。你是怎么做到的?

public class RollOff {
      public static void main(String[] args) throws IOException{

        int numPeople;
        int a;


        System.out.println("How many people will play the game?");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        numPeople = Integer.parseInt(s);

        if ((numPeople >= 2) && (numPeople <= 10)) {
            Person[] p = new Person[numPeople];
            for (a = 0; a < numPeople; a++) {
                p[0] = new Person(a);
            }

        }

    }
}

public class Game extends RollOff{
    int numPeople;
    int a;


    void PlayGame() {

  }

}

4 个答案:

答案 0 :(得分:3)

您需要使用参数来执行此操作:

void playGame(Person[] p){
    ...
}

现在只需致电

public static void main(String[] args){
    ...
    game.playGame(p);
}

因为playGame不是静态方法,所以您需要将其设置为静态并调用Game.playGame(p),否则您需要创建一个Game实例:Game game = new Game()然后调用{ {1}},如上例所示。

答案 1 :(得分:1)

public void play(Person[] person) {

// code
}

// The call
play(person);

答案 2 :(得分:1)

您只需将一个Person数组参数添加到PlayGame

即可
 void playGame(Person[] personArray){//logic of the method}

然后你所要做的就是通过创建类Game的新实例来调用main方法中的playGame方法

Game game = new Game();
game.PlayGame(p);

这里“p”是你的人阵。

答案 3 :(得分:0)

主类应该创建一个Game实例,并将玩家数组传递给构造函数:

Game game = new Game(p);
game.playGame();

Game类应该具有以下字段和构造函数:

private Person[] players;

public Game(Person[] players) {
    this.players = players;
}

请注意,方法应该以小写字母开头,以遵循Java命名约定,并且您的循环有一个错误:它总是设置数组的第一个元素,而不是初始化每个元素。

最后,为变量赋予有意义的名称:playersp更具可读性。

相关问题