我在比较数组元素的值时遇到问题。 例如我想比较索引 0 和索引 2、索引 1 和索引 3 的值,依此类推。 使用下面的代码,我想得到 numOf DifferentShape 的结果是 2,但我得到 3。 我怎么解决这个问题? :-(
int numOfdifferentShape=0;
myArray = {40.0, 40.0, 40.0, 40.0, 80.0, 40.0, 40.0, 40.0}
for (int a=0; int a<myArray.size(); a=a+2)
{
for (int b=a+2; b<myArray.size; b=b+2)
{
if (!(myArray.get(a).equals(myArray.get(b) && myArray.get(a+1).equals(b+1)))
numOfdifferentShape++;
break;
}
}
最佳答案
这段代码中有几个语法错误,但由于 TofuBeer 已经在注释中指出了这些错误,所以我将继续讨论设计和逻辑。
从代码来看,我假设您没有太多 Java 经验,也许根本没有编程经验。所以我要在这里慢慢讲。我希望我的解释不会侮辱您。
您说您正在尝试找出数组中存储的对象(作为两个整数)有多少是相等的。为此,您必须跟踪您已经看到的独特物体。然后,将每个对象与唯一对象列表进行比较,如果与其中任何一个都不匹配,则将其添加到列表中。这是基本算法。
现在,您是否注意到我在描述中一直使用“对象”这个词?当这种情况发生时,通常意味着你应该去上课。我会做一个像这样的简单的,保存两个整数:
class Box { // or whatever the objects are called
private final int height;
private final int width;
public Box(int h, int w) {
height = h;
width = w;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Box))
return false;
Box b = (Box) other;
return b.height == height && b.width == width;
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + this.height;
hash = 97 * hash + this.width;
return hash;
}
}
尝试理解这段代码的每个部分的作用(特别是如果这实际上是你的作业)。完成后,请继续进行下一部分:进行您想要进行的计算。
假设您有一个 Boxes 数组,如下所示:
Box[] boxes = {
new Box(40, 40), new Box(40, 40), new Box(80, 40), new Box(40, 40)
};
(我无法判断您使用的是数组还是列表,所以我只是选择一个来演示。)
我已经给出了查找唯一项数量的算法,因此我将向您展示如何编写它:
List<Box> unique = new ArrayList<Box>();
for (Box box : boxes) {
if (!unique.contains(box)) { // this is why I implemented equals() and hashCode()!
unique.add(box);
}
}
int numOfDifferentShape = unique.size();
这比尝试跟踪每个对象的两个整数要容易得多,而且它的优点是您不会混淆数组索引。
您可以使用Set
更轻松地做到这一点。它看起来像这样:
Set<Box> boxSet = new HashSet<Box>();
for (Box b : boxes)
boxSet.add(b);
int numOfDifferentShape = boxSet.size();
请注意,最后两个片段使用 Java 1.5 中的功能,所以我不知道你以前是否遇到过它们。
这会让事情变得更清晰吗?
关于java - 比较同一数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/702513/