Returns the mapping of faces to letters for this die ( how can i code this) new to java [closed]

StackOverflow https://stackoverflow.com/questions/19436909

  •  01-07-2022
  •  | 
  •  

質問

Returns the mapping of faces to letters for this die. The faces are identified using the Integer values 1 through 6, and the returned map is sorted on its keys (the face numbers). For example, the die with faces:

1, 2, 3, 4, 5, 6

having letters:

C, M, I, O, U, T

would return the map whose toString method would produce the following string:

{1=C, 2=M, 3=I, 4=O, 5=U, 6=T}

Clients are unable to modify the mapping of faces to letters using the returned map; i.e., modifying the returned map has no effect on the die.

Returns: a sorted map of the faces to letters

役に立ちましたか?

解決

final class Die
{

  private final Map<Integer, Character> die = new HashMap<>();

  Die(CharSequence faces)
  {
    for (int idx = 0; idx < faces.length(); ++idx)
      die.put(idx + 1, faces.charAt(idx));
  }

  SortedMap<Integer, Character> facesToLetters()
  {
    return new TreeMap<>(die);
  }

  public static void main(String... argv)
    throws Exception
  {
    Die die = new Die("CMIOUT");
    System.out.println(die.facesToLetters());
  }

}

他のヒント

Maybe something like this??

Map<Integer, Character> dieMap = new Hashmap<Integer, Character>();

// ..build the map..

public String toString() {
  StringBuilder builder = new StringBuilder();
  for (Map.Entry<Integer, Character> entry : dieMap.entrySet()) {
    // append entry.getKey() and entry.getValue() how you want
  }
  return builder.toString();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top