简体   繁体   中英

Development of monopoly game

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 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...

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,......]

Override Field 's toString() to return the name, ie

public String toString() {
  return name;
}

What you get (eg test.Field@2a139a55 ) is the default implementation of toString() which can be found in Object :

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

You missed the

Moreover, there should be a method with the signatur public String toString(),

part of your task.

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 +"]");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM