java - 使用字符索引 HashMap 时出现 NullPointerException

标签 java string nullpointerexception hashmap character

我正在编写一个英语到莫尔斯翻译器,每次运行时都会出现错误:

Exception in thread "main" java.lang.NullPointerException
    at java.lang.String.concat(Unknown Source)
    at Code.translate(Code.java:49)
    at Code.<init>(Code.java:34)
    at Morse.main(Morse.java:8)

我试过调试。这是有问题的函数:

String translate(String phrase, HashMap map) {   // line 37
        //String to contain the morse code
        String morse = "";
        //Char array to contain the English phrase
        char[] phraseList = new char[(int)phrase.length()];
        //Fill the char array
        phraseList = phrase.toCharArray();
        //Loop through the array and concat the morse string with the value returned from the key
        for (int x =0; x < phrase.length(); x++) {
            if(phraseList[x] == ' ') {
                morse.concat("  ");
            } else {
                //Here's where the error is produced
                morse.concat((String) map.get(phraseList[x]));
            }
        }
        return morse;
    }

当代码到达“else”条件时产生错误。这是设置传递给此函数的 HashMap 的构造函数:

HashMap<String,String> codeMap = new HashMap<>();
//Gets passed a string phrase from the main class
public Code(String phrase) throws FileNotFoundException {   //line 14
        String filePath;
        String letter;
        String code;
        //Creates the object that reads the file location
        Scanner fileLocate = new Scanner(System.in);
        System.out.println("Enter file path of morse code");
        //Object reads file location
        filePath = fileLocate.nextLine();
        //Create file object
        filePath=filePath.replace("\\","/");
        File morse = new File(filePath);
        //Create scanner object that reads the file
        Scanner fileRead = new Scanner(morse);
        //Loop to read the file and store the info as a key/value pair in a hashmap
        while (fileRead.hasNext()) {
            letter = fileRead.next().toLowerCase();
            code = fileRead.next();
            codeMap.put(letter, code);
        }   
        translate(phrase,codeMap);
    }

HashMap 充满了正确的小写值,char 数组充满了短语的小写字符,但由于某种原因它仍然会产生错误.任何关于我做错了什么的建议将不胜感激。

最佳答案

尝试

morse.concat((String) map.get( Character.toString(phraseList[x]) ));
                          //  ^^^^^^^^^^^^^^^^^^^^ added this

您的 map 由 String 索引,但由于类型删除,translate 不知道这一点。您正在使用 char 而不是 String 进行索引。这意味着你得到一个 autoboxed Character ,这将不是您输入的 String。因此, map 将不包含您期望的条目,并将返回 null空指针异常

解释:根据this answerhashCodeHashMap中的第一个校验。之后,Object.equals() 用于在映射中查找键。两者 String.equals(Character)Character.equals(String)将返回错误。因此,即使 String("a")Character('a')hashCode 值可能相同,但这两个是不被认为是相等的,所以它们不能作为键互换使用。

关于java - 使用字符索引 HashMap 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38268726/

相关文章:

java - 如何在 Java 程序中从 IdP-ADFS 获取用户?

java - 从露天的 jboss 7 发送文件

java - 我如何强制 MyEclipse 将 JavaScript 文件热部署到我的 JBoss 实例?

arrays - 将长字符串转换为数组中均匀分割的索引

java - UTF8 字符串到 byte[],每个字符作为单个字节

java - 什么是NullPointerException,我该如何解决?

java - 使用脚本ElasticSearch API的更新不接受Scala Map

Matlab 将字符串 "aaa"转换为 ["a", "a", "a"] 数组

java - NullPointerException 通过 Java 三元运算符的自动装箱行为

android - ActionBar 搜索的 ExpandedView 上的空指针