我不明白为什么这段代码会输出ERROR。怎么可能呢?
Set<Set<Place>> clusters = new HashSet<Set<Place>>();
...
Set<Place> max1 = null;
Set<Place> max2 = null;
double maxSim = 0;
for (Set<Place> placesSet : clusters) {
for (Set<Place> placesSet2 : clusters) {
if (placesSet != placesSet2) {
double sim = calculateSim(placesSet, placesSet2);
if (sim >= maxSim) {
maxSim = sim;
max1 = placesSet;
max2 = placesSet2;
}
}
}
}
if (!clusters.remove(max2)) {
System.out.println("ERROR");
}
EDIT 现在我检查sim是否小于0并且cluster有多个元素。仍然得到错误
Set<Place> max1 = null;
Set<Place> max2 = null;
double maxSim = 0;
for(Set<Place> placesSet : clusters) {
for(Set<Place> placesSet2 : clusters) {
if(!placesSet.equals(placesSet2)) {
double sim = calculateSim(placesSet, placesSet2);
if(sim < 0) sim = 0;
if(sim >= maxSim) {
maxSim = sim;
max1 = placesSet;
max2 = placesSet2;
}
}
}
}
if(!clusters.remove(max2) && clusters.size() >= 1) {
System.out.println("ERROR");
}
下一页编辑:
仍然错误:(
Set<Place> max1 = null;
Set<Place> max2 = null;
double maxSim = 0;
for(Set<Place> placesSet : clusters) {
for(Set<Place> placesSet2 : clusters) {
if(!placesSet.equals(placesSet2)) {
double sim = calculateSim(placesSet, placesSet2);
if(sim < 0) sim = 0;
if(sim >= maxSim) {
maxSim = sim;
max1 = placesSet;
max2 = placesSet2;
}
}
}
}
if(max2 != null && !clusters.remove(max2) && clusters.size() > 1) {
System.out.println("ERROR");
}
答案 0 :(得分:3)
似乎有两种可能性:
calculateSim()
返回负值。由于sim
永远不会是&gt; = 0,因此永远不会执行您的if语句,max2
将为空。cluster
有0个或1个元素。如果没有元素,那么循环将永远不会执行。如果有一个元素,循环将执行,但该元素将等于它自己,所以你的第一个元素将失败。我建议使用anding print语句来监控代码的执行
编辑:请实际在您的代码中插入print语句:
Set<Place> max1 = null;
Set<Place> max2 = null;
double maxSim = 0;
System.out.printf("clusters has %d elements:%s%n",clusters.size,clusters);
for(Set<Place> placesSet : clusters) {
for(Set<Place> placesSet2 : clusters) {
System.out.printf("%ncomparing %s and %s%n",placesSet,placesSet2);
if(!placesSet.equals(placesSet2)) {
System.out.println("The sets are not the same");
double sim = calculateSim(placesSet, placesSet2);
System.out.printf("The sim of the sets is %f%n",sim);
if(sim < 0) sim = 0;
System.out.printf("Comparing to the max sim %f%n",maxSim);
if(sim >= maxSim) {
System.out.println("Found new max sim");
maxSim = sim;
max1 = placesSet;
max2 = placesSet2;
}
}
}
}
System.out.printf("The max is %s%n",max2);
if(max2 != null && !clusters.remove(max2) && clusters.size() > 1) {
System.out.println("ERROR");
}
答案 1 :(得分:0)
我相信答案是你所有的地方都必须相同(包含相同的地方)。因此,无论PlaceSet2是否为同一个实际对象,placesSet始终等于placesSet2。