【发布时间】:2017-11-19 11:57:44
【问题描述】:
我有一个家庭作业,但我对 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'
}
Game Class -- 另一个版本(将所有内容放在 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
Player 类:具有 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; }
【问题讨论】:
-
您实际使用的版本在哪里?并放置完整的错误堆栈跟踪
-
为什么 setter 的名字是
setName定义的却叫setPName。看起来你混淆了几个教程中的代码。
标签: java arrays class object getter-setter