【发布时间】:2018-10-25 23:08:22
【问题描述】:
我正在尝试一种简单的方法来使用映射为所有字母分配一个值。我尝试使用 for 循环,但是当我尝试获取字母的值时,我收到 null。
import java.util.*;
/*
* This class scores words in the game of Scrabble.
* A word's score is the total of its individual tile scores.
*/
public class ScrabbleScorer {
private final Map<Character, Integer> tileScores;
public ScrabbleScorer() {
char[] tiles = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
// TODO: initialise the array of individual letter scores
int[] scores = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
// TODO: create the `tileScores` map
tileScores = new HashMap<Character, Integer>();
// TODO: populate the `tileScores` map using the `tiles`
// and `scores` arrays
for(int i=0; i<scores.length; i++){
tileScores.put(tiles[i],scores[i]);
};
System.out.println(tileScores.get("A"));
}
【问题讨论】:
-
"A"是String,而不是Character。你需要改写'A'。
标签: java loops dictionary for-loop