简体   繁体   English

比较同一数组的元素

[英]Compare elements of the same array

I have problem with comparing the value of array elements.我在比较数组元素的值时遇到问题。 eg I wanted to compare the value of index 0 and index 2, and index 1 to index 3 and so on.例如,我想比较索引 0 和索引 2 的值,以及索引 1 和索引 3 的值,依此类推。 With the code below I suppose to get the result of numOfdifferentShape is 2 but I get 3. How can I solve this problem?使用下面的代码,我想得到 numOfdifferentShape 的结果是 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;
   }
}

There are several syntax errors in this code, but since TofuBeer has already pointed them out in the comments, I'll move on the the design and logic.这段代码有几个语法错误,但由于 TofuBeer 已经在评论中指出了它们,我将继续进行设计和逻辑。

Going from the code, I'm assuming you don't have much experience with Java, and perhaps not with programming at all.从代码来看,我假设您对 Java 没有太多经验,也许根本没有编程经验。 So I'm going to go slowly here.所以我这里慢慢来go。 I hope you aren't insulted by my explanations.我希望你不会被我的解释侮辱。

You say you are trying to find out how many of the objects which you are storing (as two ints) in your array are equal.你说你试图找出你在数组中存储的对象(作为两个整数)有多少是相等的。 To do this, you have to keep track of what unique objects you have already seen.为此,您必须跟踪您已经看到的独特对象。 Then you compare each object the list of unique objects and, if it doesn't match any of them, add it to the list.然后,您将每个 object 与唯一对象列表进行比较,如果不匹配,则将其添加到列表中。 This is the basic algorithm.这是基本算法。

Now, have you noticed that I keep using the word "object" in my description?现在,你注意到我在描述中一直使用“对象”这个词吗? When that happens, it usually means you should be making a class.发生这种情况时,通常意味着您应该制作 class。 I would make a simple one like this, holding the two integers:我会做一个这样的简单的,持有两个整数:

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;
    }
}

Try to understand what each part of this code does (especially if this is actually your homework).试着理解这段代码的每一部分是做什么的(特别是如果这实际上是你的作业)。 Once you've got it, move on to the next part: doing the calculation that you were trying to do.一旦你得到它,继续下一部分:做你想做的计算。

Let's say you have an array of Boxes, like this:假设您有一个 Box 数组,如下所示:

Box[] boxes = {
    new Box(40, 40), new Box(40, 40), new Box(80, 40), new Box(40, 40)
};

(I can't tell if you're using an array or a list, so I'm just picking one to demonstrate.) (我不知道你使用的是数组还是列表,所以我只是选择一个来演示。)

I already gave the algorithm for finding the number of unique items, so I'll show you how I would write it:我已经给出了查找唯一项目数量的算法,所以我将向您展示我将如何编写它:

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();

This is much easier than trying to keep track of two ints for each object, plus it has the advantage that you can't get your array indices confused.这比尝试为每个 object 跟踪两个整数要容易得多,而且它的优点是您不会混淆数组索引。

You could do this even more easily with a Set .您可以使用Set更轻松地做到这一点。 It would look something like this:它看起来像这样:

Set<Box> boxSet = new HashSet<Box>();
for (Box b : boxes)
    boxSet.add(b);
int numOfDifferentShape = boxSet.size();

Note that these last two snippets use features from Java 1.5 , so I don't know if you've run into them before.请注意,最后两个片段使用Java 1.5中的功能,所以我不知道您之前是否遇到过它们。

Does this make things clearer?这会让事情变得更清楚吗?

for (int i = 0; i < (myArray.size() - 2); ++i)
{
    if (myArray[i] != myArray[i + 2])
        ++numOfdifferentShapes;
}
  1. You have two loops, your description suggests you only want one.你有两个循环,你的描述表明你只想要一个。
  2. You need to do bounds checking - do you want the n+2 to wrap to the start to the start of the array when it exceeds the length?您需要进行边界检查 - 当它超过长度时,您是否希望 n+2 环绕到数组的开头到开头?

I think you have a parentheses problem.我认为你有一个括号问题。 You wrote:你写了:

if (!(myArray.get(a).equals(myArray.get(b) && myArray.get(a+1).equals(b+1)))

when I think you mean:当我认为你的意思是:

if (!(myArray.get(a).equals(myArray.get(b)) && myArray.get(a+1).equals(b+1))

Also, in the same line, instead of:此外,在同一行,而不是:

equals(b+1)

don't you mean你不是说

myArray.get(b+1)

I have array list eg {40,40,80,20,40,40} I wanted to compare the elements.我有数组列表,例如 {40,40,80,20,40,40} 我想比较元素。 Even number of index (eg index 0, index 2, index 4 etc) represents Height of an object and Odd number of Index (eg index 1, index 3 ec) represent Width of an object.偶数索引(例如索引 0、索引 2、索引 4 等)表示 object 的高度,奇数索引(例如索引 1、索引 3 ec)表示 object 的宽度。 So, with the code above, Object 1 (index 0 and 1).因此,使用上面的代码,Object 1(索引 0 和 1)。

Why not make an array of a Dimension class, something like this:为什么不创建一个维度 class 的数组,如下所示:

public class Dimension
{
    private final int width;
    private final int height;

    public Dimension(final int w, 
                     final int h)
    {
        width  = w;
        height = h;
    }

    public int getWidth()
    {
        return (width);
    }

    public int getHeight()
    {
        return (height);
    }
}

then do a for loop something like this:然后做一个这样的for循环:

for(int i = 0; i < array.length; i += 2)
{
    final Dimension a;
    final Dimension b;

    a = array[i];
    b = array[i + 1];

    // compare a.getLength() to b.getLength() 
    // or 
    // compare a.getWidth() to b.getWidth() 
}

It is usually a bad idea to try and be "tricky" - saying even ones are with and odd ones are length is being tricky... bad idea IMO.尝试变得“棘手”通常是一个坏主意 - 说偶数和奇数长度是棘手的......IMO坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM