【发布时间】:2017-03-10 00:57:24
【问题描述】:
以下是创建整数集的程序,我相信我一切正常,除了我的 intersectionWith 函数不能正常工作。
这是我的 IntSet 代码:
public class IntSet{
private final int MAXALLOWEDSETVALUE=2000;
private boolean [] data = new boolean[MAXALLOWEDSETVALUE+1];
public IntSet(int... elts) {
for(int iteration = 0; iteration < elts.length; iteration++) {
if(elts[iteration] <= MAXALLOWEDSETVALUE)
data[elts[iteration]] = true;
}
}
public IntSet(IntSet source){
System.arraycopy(source.data, 0, this.data, 0, MAXALLOWEDSETVALUE);
}
public void setTo(IntSet source){
System.arraycopy(source.data, 0, this.data, 0, MAXALLOWEDSETVALUE);
}
public IntSet intersectionWith(IntSet other) {
IntSet newSectionSet = new IntSet(this);
for(int iteration = 0; iteration < MAXALLOWEDSETVALUE; iteration++) {
if(newSectionSet.data[iteration] == true && other.data[iteration] == true) {
newSectionSet.data[iteration] = true;
}
}
return newSectionSet;
}
}
还有我的程序代码:
import java.lang.Math;
import java.util.Random;
public class Program {
public static void main(String [] args){
Random rng = new Random();
rng.setSeed(0);
IntSet is1, is2, is3, is4;
is1 = new IntSet(2,4,5);
is2 = new IntSet(1,2,5);
is3 = new IntSet();
is4 = new IntSet(is2);
is3.setTo(is1.intersectionWith(is2));
System.out.print("is3 (intersection): ");
System.out.println(is3.toString()); // should be 2 5
}
}
一切似乎都对我有用,除了我的 intersectionWith 函数。
这是我运行代码时输出的内容:
is3 (intersection): {2, 4, 5, }
但它需要的只是 {2, 5}
我不确定我是如何得到这个错误的。
我的 intersectionWith 函数应该基于两个集合创建一个新集合。只有当两个集合中都存在该元素时,它才会将一个元素添加到新集合中。
【问题讨论】:
-
这是太多的代码,无法期望人们为您完成。您需要进行调试以缩小问题范围。
-
很抱歉,我实际上应该删除大部分代码,因为它们无关紧要
-
我不知道问题是什么,但是 2 cmets: 1.
newSectionSet.toString();应该做什么?您制作了该集合的字符串版本,然后将其丢弃。 2. 你几乎不应该写== true;在 99.9% 的情况下它是多余的。if的目的是检查它的条件是否为真。 -
根据上面的代码
is1没有任何元素