gpt4 book ai didi

java - 如何获取和设置对象数组中的名称?

转载 作者:行者123 更新时间:2023-12-01 07:47:47 26 4
gpt4 key购买 nike

我有一个家庭作业,但我对 Java 很陌生,过去两天一直在尝试创建玩家对象数组、设置名称并获取名称。

但是无论我尝试什么,我都会遇到错误。我看了很多教程,并准确地复制了他们所做的事情,但它不起作用。如何正确创建数组并获取/设置名称?

我有一个 Game 类和一个 Player 类:

游戏类——一个版本:

Player[] players = new Player[3];

//All the tutorials I've seen show both these types of putting names in:

players[0] = new Player();

//followed by:
players[0].setName("name");
//or...

players[0] = new Player("human");

//my errors on both: unknown class 'players'...
//unexpected token... invalid method... etc etc

Gmae 类 - 不同版本(使用方法):

//for the homework, I'm expected to put it all into a method
//ideally I'd be using the setName method from the Players class (below)
//but that doesn't work here

void createPlayers(Player[] players) {
for (Player p : players) {
players[0] = new Player("human");
players[1] = new Player("Greg");
players[2] = new Player("Susan");
}
}

public static void main(String[] args) {
Game obj = new Game();

//I had to change Players[] to static to get a printout but it's not supposed
//to be static

//I tried these separately to check output
//I need to be able to get the name of a player

obj.createPlayers(players); //no output

for (Player pl : players) {
System.out.println("Name = " + pl); //null null null
}
System.out.println(obj.players[0]); //null
obj.player[0].getName(); //cannot resolve symbol 'player'
}

游戏类 - 另一个版本(将所有内容放在 main 中):

public static void main(String args[]) {
Main game = new Main();

Player p0 = new Player("Jeff"); //it errored if I didn't put a name
Player p1 = new Player("Susan"); //but I need to be able to change names
Player p2 = new Player("Michael");

Player[] players = new Player[3];
players[0] = p0;
players[1] = p1;
players[2] = p2;

p2.setPName("Alan");
System.out.println(p2.getPName()); //output: null

玩家类:具有 getter 和 setter,我理想情况下会使用它们来获取和设置玩家名称,但我不知道如何使它们在我的 Game 类中工作。

private String name;

Player (String name) { this.name = name; }

public void setName(String name) { this.name = name; }

public String getName() { return name; }

最佳答案

对您的 Game 类进行简单修改后,我得到了这个,这几乎可以实现您想要做的事情:

public class Game {

void createPlayers(Player[] players) {
Player player1 = new Player();
player1.setName("human");

Player player2 = new Player();
player2.setName("Greg");

Player player3 = new Player();
player3.setName("Susan");

players[0] = player1;
players[1] = player2;
players[2] = player3;
}

public static void main(String[] args) {
Player[] players = new Player[3];

Game obj = new Game();
obj.createPlayers(players);

for (Player pl : players) {
System.out.println("Name = " + pl.getName());
}
}
}

关于java - 如何获取和设置对象数组中的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47376557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com