我正在尝试为自己构建一个Set,只使用相交,联合和打印作为方法。
我的测试代码是
public static void main(String[] args)
{
double[] a = {1,2,3,4,101.9};
double[] b = {3,7,13,901,-29.1,0.0001};
NumSet test;
test = new NumSet(a);
test.intersect(a, b);
System.out.println("tried intersect [1,2,3,101.9], [3,7,13,901,-28.8,0.001]");
test.print();
System.out.println("tried test.print()");
test.union(a,b);
System.out.println("tried union [1,3,3,5,7,9], [3,5,7,13]");
}
给了我一个
tried intersect [1,2,3,101.9], [3,7,13,901,-28.8,0.001]
0.0,0.0,0.0,out of bounds 4 >= 4 or 4 < 0
0.0tried test.print()
tried union [1,3,3,5,7,9], [3,5,7,13]
这很奇怪,因为我的印刷与打印第二个句子无关。
public void print()
{
for (int i = 0; i < set.size() - 1; i++)
{
System.out.print(set.lookup(i) + ",");
}
System.out.print(set.lookup(set.size()));
}
这是我的打印方法。 并且当班级正在扩展另一个班级时,
public class NumSet extends NumArrayList
{
NumList set;
public NumSet(double[] sth)
{
set = new NumArrayList();
for (int i = 0; i < sth.length; i++)
{
set.insert(i, sth[i]);
}
set.removeDuplicates();
}
int numSet = 0;
public NumList intersect(double[] S1, double[] S2)
{
for (int i = 0; i < S1.length; i++)
{
for(int j = 0; j < S2.length; j++)
{
if (S1[i] == S2[j])
{
set.insert(numSet, S1[i]);
numSet++;
}
}
}
set.removeDuplicates();
return set;
}
public NumList union(double[] S1, double[] S2)
{
for (int i = 0; i < S1.length; i++)
{
set.insert(1, S1[i]);
}
for (int i = 0; i < S2.length; i++)
{
set.insert(1, S2[i]);
}
set.removeDuplicates();
return set;
}
我去那里检查了打印方法。
public void print()
{
for (int i = 0; i < numItems - 1; i++)
{
System.out.println(items[i]+ ",");
}
System.out.println(items[numItems-1]);
}
让我傻眼了,为什么我的错误信息就是这样。
我的印刷品在哪里提到这样一个奇怪的信息?
答案 0 :(得分:0)
您在上一篇-1
声明中遗漏了print
:
System.out.print(set.lookup(set.size()));
应该是:
System.out.print(set.lookup(set.size() - 1));
请记住,lookup
索引从零开始,因此使用set.size()
确实超出范围。