比較同一數組的元素 (Compare elements of the same array)


問題描述

比較同一數組的元素 (Compare elements of the same array)

I have problem with comparing the value of array elements. e.g. I wanted to compare the value of index 0 and index 2, and index 1 to index 3 and so on. With the code below I suppose to get the result of numOfdifferentShape is 2 but I get 3. How can I solve this problem? :‑( 

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

‑‑‑‑‑

參考解法

方法 1:

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.

Going from the code, I'm assuming you don't have much experience with Java, and perhaps not with programming at all. So I'm going to go slowly here. 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. 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. 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[] 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.

You could do this even more easily with a 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.

Does this make things clearer?

方法 2:

for (int i = 0; i < (myArray.size() ‑ 2); ++i)
{
    if (myArray[i] != myArray[i + 2])
        ++numOfdifferentShapes;
}

方法 3:

  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?

方法 4:

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)

方法 5:

  

I have array list e.g.   {40,40,80,20,40,40} I wanted to   compare the elements. Even number of   index (e.g. index 0, index 2, index 4   etc) represents Height of an object   and Odd number of Index (e.g. index 1,   index 3 ec) represent Width of an   object. So, with the code above,   Object 1 (index 0 and 1).

Why not make an array of a Dimension class, something like this:

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(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.

(by JessyMichael MyersFerdinand BeyerJeeBeeJeffHTofuBeer)

參考文件

  1. Compare elements of the same array (CC BY‑SA 3.0/4.0)

#java #arrays #comparison






相關問題

電子郵件地址中帶有 + 字符的 Java 郵件 (Java mail with + character in email address)

如何快速原型化 Java 代碼? (How to quickly prototype Java code?)

如何使用 Maven 在目標(SVN-)服務器上創建 Javadoc? (How to create Javadoc on the target (SVN-) server using Maven?)

為什麼檢查二叉樹有效性的解決方案不起作用? (Why the solution for checking the validity of binary tree is not working?)

Selenium webdriver通過第一個數字找到texy (Selenium webdriver find texy by first digits)

setOnClickListener 沒有在圖像視圖上被調用 (setOnClickListener is not getting called on image view)

繪製多邊形:找不到錯誤 (Drawing Polygon : unable to find error)

半透明 JButton:對像出現在背景中 (Semi-Transparent JButton: Objects appear in Background)

比較同一數組的元素 (Compare elements of the same array)

Java 屏幕截圖小程序 (Java screen capture applet)

Minecraft 1.8.9 Forge Modding 的Java 開發工具包,需要什麼JDK/JRE,代碼是否正確? (Java Development Kit with Minecraft 1.8.9 Forge Modding, What JDK/JRE Is Needed, Is Code Correct?)

java while (resultset.next()) 不返回同一列中的所有數據 (java while (resultset.next()) does not return all data in the same column)







留言討論