【问题标题】:null point exception error in hashmap [duplicate]哈希图中的空点异常错误[重复]
【发布时间】:2017-10-26 20:27:04
【问题描述】:

我在这里不断收到一个空点异常,我不知道我的代码有什么问题。我有一个构造函数,可以将 { x=-1 y=-2.0 z=3d } 之类的 String 解析为 Vector(_hmVar2Value) 的内部 HashMap 表示。

public Vector(String s) {
    String[] splitString = s.split(" ");
    for (int i=0;i<splitString.length-2;i++) {
        String[] str=splitString[i+1].split("=");
        double x = Double.parseDouble(str[1]);
        _hmVar2Value.put(str[0],x);
    }
}

【问题讨论】:

  • 请添加语言标签
  • 你可能忘了初始化你的 hashmap:_hmVar2Value

标签: string hashmap


【解决方案1】:

我已经运行了您的代码,并且运行良好。 你初始化你的哈希图了吗?

试试这样的

是的,你已经声明了它,但还没有初始化它。试试这样的

public OtherClass(String s) {
            _hmVar2Value = new HashMap<String,Double>();
            String[] splitString = s.split(" ");
            for (int i=0;i<splitString.length-2;i++) {
                String[] str=splitString[i+1].split("=");
                double x = Double.parseDouble(str[1]);
                _hmVar2Value.put(str[0],x);

            }
    System.out.print(_hmVar2Value);



  }

【讨论】:

  • 私有 HashMap _hmVar2Value;虽然我有这个以及最初为空向量的构造函数,但我一直收到错误
  • 是的,你已经声明了它但是还没有初始化它。我已经用一些代码更新了我的答案。希望这会有所帮助
  • 我添加了初始化。 nullpointerror 现在消失了,但我不断收到 ArrayIndexOutOfBoundsException。
  • 好吧,如果没有输入,那我就帮不了你了。但我从 String[] str=splitString[i+1].split("=");双 x = Double.parseDouble(str[1]);你必须调试才能发现:)
猜你喜欢
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
相关资源
最近更新 更多