【问题标题】:Nullpointer Exception in HashMap [duplicate]HashMap 中的空指针异常 [重复]
【发布时间】:2017-05-04 21:51:36
【问题描述】:

我对java很陌生。我试图从文件中获取输入,并将文件中的参数设置为 hashmap 键和值。但它在我从行中拆分参数的行上返回空指针异常。这是我的代码:

public class hashtable{
    public static void main(String[] args) throws Exception{
        HashMap nodes = new HashMap<String,String>();
        String filename = args[0];
        FileReader file = null;
        BufferedReader reader = null;
        try{
          file = new FileReader(filename);
          reader = new BufferedReader(file);
          String line;
          line = reader.readLine();
            while(line != null){
             line = reader.readLine();
             String []arguments = line.split("\\s+");
             nodes.put(arguments[2],arguments[1]);
            }
        }
        catch(IOException e){}
        finally{
          reader.close();
        } 

        for(int i = 0 ; i < 5;i++){
            System.out.println(nodes.get(i));
        }
    }
}

我哪里出错了? 任何帮助将不胜感激。

【问题讨论】:

  • @JoeC 不,不是。请阅读问题。
  • 我已经阅读了这个问题。我认为没有理由相信这不是重复的。如果您告诉我为什么该问题的答案不能回答您的问题,那么我们可以进一步讨论。
  • 对于初学者,您需要包含显示确切位置引发异常的堆栈跟踪。

标签: java hashmap


【解决方案1】:

您正在检查第 1 行是否不为空,但随后您继续阅读并使用第 2 行。将下一个readLine() 移到循环末尾:

line = reader.readLine();
while(line != null){
    String []arguments = line.split("\\s+");
    nodes.put(arguments[2],arguments[1]);
    line = reader.readLine();
}

或者,更常规地,您可以将两个readLine() 语句合并到循环条件中:

while((line = reader.readLine()) != null) {

【讨论】:

  • 啊,我太愚蠢了。非常感谢
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 2014-07-28
相关资源
最近更新 更多