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());
}
}
Returns the mapping of faces to letters for this die ( how can i code this) new to java [closed]
题
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
解决方案
其他提示
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();
}
不隶属于 StackOverflow