【发布时间】:2014-08-13 09:53:53
【问题描述】:
重新发布一个更详细的问题。问题是发生在 clusterer.next() 处的 nullPointerException。以下是该程序的简化版本,希望您能注意到问题所在。
public class Clustering {
private DistanceMeasure measure; //Manhattan or Euclidean
private ClusterMethod method; //SingleLinkage or CompleteLinkage
private Clusterer clusterer;
public static void main(String[] args) {
new Clustering().start();
}
Clustering() {
measure = new Manhattan();
method = new SingleLinkage(measure);
clusterer = new Clusterer(method);
}
void start() {
clusterer = setMethod();
clusterer.next(); //would use the ClusterMethod to do some calculations; the nullException occurs here
}
Clusterer setMethod() {
measure = new Euclidean();
if (method.getClass().getSimpleName().equals("SingleLinkage")) {
method = new CompleteLinkage(measure);
}
else method = new SingleLinkage(measure);
return new Clusterer(method);
}
}
public class Clusterer {
private ClusterMethod method;
Clusterer(ClusterMethod method) {
this.method = method;
}
void next() {
System.out.println(method.calculateDistance(0,1); //calculateDistance simply returns the 'distance' between 2 numbers.
}
}
如果我不使用 setMethod(),上面的代码可以完美运行;
【问题讨论】:
-
请添加堆栈跟踪。
-
在 finalPAD.Clustering.performClusterStep(Clustering.java:91) 处 finalPAD.Clusterer.getClusterStep(Clusterer.java:23) 处的线程“main”java.lang.NullPointerException 异常。 processEvents(Clustering.java:54) 在 finalPAD.Clustering.proceedClustering(Clustering.java:48) 在 finalPAD.Clustering.start(Clustering.java:42) 在 finalPAD.Clustering.main(Clustering.java:34) where getClusterStep( ) 在我的示例中是 next()
-
贴出正确的代码sn-p:finalPAD.Clusterer.getClusterStep(Clusterer.java:23是错误发生的地方,你的代码sn-p中没有显示出来
-
除非你想让我发布 20 类代码,请耐心等待。我的实际程序中堆栈跟踪中的 getClusterStep(Clusterer.java:23) 行对应于我的示例中的“System.out.println(method.calculateDistance(0,1);”。就像我说的,如果我不调用 setMethod() 所以我相信我处理对象引用的方式在某处是错误的。
-
Clustering.performClusterStep 中发生了什么?