【问题标题】:NullPointerException when indexing HashMap with character使用字符索引 HashMap 时出现 NullPointerException
【发布时间】:2016-07-08 14:07:58
【问题描述】:

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

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 数组充满了短语的小写字符,但由于某种原因它仍然会产生错误。任何关于我做错了什么的建议将不胜感激。

【问题讨论】:

  • 提示:该行包含 3 个可能引发 NPE 的潜在原因。因此,首先剖析这些语句,以了解您使用的哪些对象实际上是空的。
  • 您能告诉我们Codetranslate从哪一行开始吗?
  • 并提示代码质量:构造函数从不做“真正的工作”。使用它们来创建新对象,而不是打开文件、读取内容和翻译。相反:你在你的类上放了许多小方法来做所有这些事情。奖励包括:如果您这样做,突然之间,您将能够测试所有这些小方法......一个一个,范围非常明确,而且工作量少得多。长话短说:阅读en.wikipedia.org/wiki/SOLID_(object-oriented_design) ...,尤其是SRP
  • System.out.println(morse + " " + map + " " + phraseList[x] + " " + map.get(phraseList[x]); 哪个为空?

标签: java string nullpointerexception hashmap character


【解决方案1】:

试试

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

您的地图由String 索引,但translate 由于类型擦除不知道这一点。您正在使用 char 而不是 String 进行索引。这意味着您将得到一个autoboxed Character,而不是您输入的String。因此,地图将不包含您期望的条目,并将返回null——NullPointerException 的来源。

说明:根据this answerhashCodeHashMap中的第一个检查。之后,Object.equals() 用于在映射中查找键。 String.equals(Character)Character.equals(String) 都将返回 false。因此,即使String("a")Character('a')hashCode 值可能相同,但这两者并不相等,因此它们不能互换用作键。

【讨论】:

  • 我试过了,但它说Cannot cast from char to String
  • @CS2016 对不起 --- 走在前面。试试修改后的版本。
  • @CS2016 很高兴听到这个消息!我自己也学到了一些新东西:)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
  • 2013-12-29
  • 2013-12-19
  • 2022-01-19
  • 2013-04-13
相关资源
最近更新 更多