【问题标题】:Assigning a Character an Integer Value for a Map using a 'For Loop'使用“For循环”为地图分配一个整数值
【发布时间】: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


【解决方案1】:

您的 Map 包含 Character 键,而不是 String 键。改变这个

System.out.println(tileScores.get("A"));

System.out.println(tileScores.get('A'));

【讨论】:

  • 谢谢你,非常愚蠢的错误......仍然习惯了基础知识。
【解决方案2】:

如果您真的在寻找一种简单的方法来将分数绑定到字母,我建议您利用字母集是按顺序排列这一事实,因此字母可以用于index 分数数组(记住 charnumeric 类型):

public int getScoreForLetter(char letter)
{
    return scores[letter-'A'];
}

【讨论】:

    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多