我正在尝试制作一个将通过输入的2D数组运行的程序。输出应为通过IF语句的2D数组中的所有值。双打的输出阵列应为一个可以符合正确值的尺寸。我有一个用于确定大小的循环,然后添加正确值的大小。
public static double[] getAreasGreaterThan(GeometricShape[][] haystack, double threshold) {
// TODO
int count = 0;
for (int a = 0; a < haystack.length; a++) {
for (int b = 0; b < haystack[a].length; b++) {
if(haystack[a][b].getArea() > threshold) {
count++;
}
}
}
double[] areas = new double[count];
for (int i = 0; i < haystack.length; i++) {
for (int j =0; j < haystack[i].length; j++) {
if(haystack[i][j].getArea() > threshold) {
areas[i] = haystack[i][j].getArea();
}
}
}
return areas;
}
我不断摆脱界限异常或仅接收错误的输出。我的迭代错误吗?
我认为您也可以尝试另一种方式,将输出放入列表中,然后将其转换为数组,这将更好地理解。这样:
List<Double> areaList = new ArrayList<Double>();
for (int a = 0; a < haystack.length; a++) {
for (int b = 0; b < haystack[a].length; b++) {
if(haystack[a][b].getArea() > threshold) {
areaList.add(haystack[a][b].getArea());
}
}
}
return areaList.toArray(new Double[areaList.size()]);
问题在这里,您没有正确地通过区域进行迭代。您应该有一个单独的计数器,以便在区域中的位置进行。当您的I值超过可能的对象数量时,您的错误就会弹出,每当您的I维度长于区域数量时,这些对象都会发生。例如,当您的第一个维度为长度7时,您只有3个通过3个对象,最后一个对象是在3个以上的任何一个维度中,您将会遇到错误。让我知道错误是否存在。
int areasIterable=0
for (int i = 0; i < haystack.length; i++) {
for (int j =0; j < haystack[i].length; j++) {
if(haystack[i][j].getArea() > threshold) {
areas[areasIterable] = haystack[i][j].getArea();
areasIterable=areasIterable+1;
}
}
}
我们已经简化了多少年?现在15年?
double[] getAreasGreaterThan(GeometricShape[][] haystack, double threshold) {
int count = 0;
for (GeometricShape[] gsa: haystack) {
for (GeometricShape gs: gsa) {
if (gs.getArea () > threshold) {
count++;
}
}
}
double[] areas = new double[count];
int i = 0;
for (GeometricShape[] gsa: haystack) {
for (GeometricShape gs: gsa) {
if (gs.getArea () > threshold) {
areas[i] = gs.getArea();
i++;
}
}
}
return areas;
}
不幸的是,在声明数组之前,我们需要大小。但是,我们可以将有趣的值存储在一个列表中(或向量或集合,或哪个集合可能会进一步(:
(:可以立即返回双重列表,但数组首先需要一些转换:
Double[] getAreasGreaterThan(GeometricShape[][] haystack, double threshold) {
List <Double> areas = new ArrayList <> ();
for (GeometricShape[] gsa: haystack) {
for (GeometricShape gs: gsa) {
double area = gs.getArea ();
if (area > threshold) {
areas.add (area);
}
}
}
Double[] areasAd = new Double[areas.size ()];
areas.toArray (areasAd);
return areasAd;
}
,但这是一系列双打,可能不是您需要的 - 也许您受外国或自己的API束缚。不幸的是,在盒装值和未盒装和数组/列表/...
之间的标准LIB中没有一个命令转换:double[] getAreasGreaterThan(GeometricShape[][] haystack, double threshold) {
List <Double> areas = new ArrayList <> ();
for (GeometricShape[] gsa: haystack) {
for (GeometricShape gs: gsa) {
double area = gs.getArea ();
if (area > threshold) {
areas.add (area);
}
}
}
double[] areasa = new double [areas.size()];
int i = 0; for (Double d: areas) {areasa [i] = d.doubleValue(); ++i;}
return areasa;
}