Reputation: 21
I seem to have a problem with a subtask. It's in danish so I put in the translated version of it:
- 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 fieldint 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 whatField
a player has landed on. At first it's allowed to just call the fields Field1, Field2...
My Field class look like this:
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;
}
}
In my main
method I wanted to test this. So I wrote the following:
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));
In my console I get this:
Board: [test.Field@2a139a55, test.Field@15db9742, test.Field@6d06d69c,......]
And I want this:
Board: [Field1, Field2, Field3,......]
Upvotes: 1
Views: 490
Reputation: 21586
Are you able to use java8? Then I would suggest this:
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);
}
String commaSeparatedName =
Arrays.stream(board) // all items as stream
.map(Field::getName) // for each take its name
.collect(Collectors.joining(", "); // join names with a comma
System.out.println("Board: [" + commaSeparatedNames +"]");
Upvotes: 1
Reputation: 23655
You missed the
Moreover, there should be a method with the signatur public String toString(),
part of your task.
Upvotes: 3
Reputation: 88707
Override Field
's toString()
to return the name, i.e.
public String toString() {
return name;
}
What you get (e.g. test.Field@2a139a55
) is the default implementation of toString()
which can be found in Object
:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Upvotes: 6