gpt4 book ai didi

java - 大富翁游戏开发

转载 作者:行者123 更新时间:2023-11-29 09:52:44 26 4
gpt4 key购买 nike

我好像有一个子任务有问题。它是丹麦语的,所以我放入了它的翻译版本:

  • Create a class Field, that is representing the fields of a monopoly game. Initially, Field can contain these encapsulated variables:
    • String name - short name of the field
    • int number - a number in the range[1..40]

Both variables must be initialized in a constructor, and there must only be getters, as they never will be changed after creation. Moreover, there should be a method with the signature public String toString(), so it's easy to print what Field a player has landed on. At first it's allowed to just call the fields Field1, Field2...

我的 Field 类如下所示:

public class Field {

String name;
int number;

public Field(String name, int number) {
this.name = name;
this.number = number;
}

public String getName() {
return name;
}

public int getNumber() {
return number;
}
}

在我的 main 方法中,我想对此进行测试。所以我写了以下内容:

Field[] board = new Field[40]; // a board containing 40 fields

for (int i = 0; i < board.length; i++) {
board[i] = new Field("Field" + (i + 1), i + 1);
}

System.out.println("Board: " + Arrays.toString(board));

在我的控制台中我得到了这个:

Board: [test.Field@2a139a55, test.Field@15db9742, test.Field@6d06d69c,......]

我想要这个:

Board: [Field1, Field2, Field3,......]

最佳答案

覆盖 FieldtoString() 以返回名称,即

public String toString() {
return name;
}

您得到的(例如 test.Field@2a139a55)是 toString() 的默认实现,可以在 Object 中找到:

public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

关于java - 大富翁游戏开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32947789/

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