2015-10-14 84 views
0

我想問一下,我們如何在元素內找到一個變量值的數組元素?可能嗎?如果是這樣,請告訴。假設我們有一個名爲Pt的對象:Java - 如何在屬於對象數組的對象內找到變量的值?

public class Pt { 
    private int x, y; 

    public void setCoords(int i, int j){ 
     x = i; 
     y = j; 
    } 

    public int getX(){ 
     return x; 
    } 

    public int getY(){ 
     return y; 
    } 

} 

然後我們創建一個Pt對象數組並初始化它的元素。

Pt[] point; 
point[0].setCoords(0,0); 
point[1].setCoords(1,1); 

我現在遇到的問題是如何找到座標爲(1,1)的元素?

+0

這很容易解決。給自己一個嘗試。 –

+3

我現在才意識到它。我應該簡單地循環使用getX和getY方法嗎? –

+0

這是一種可能性是... –

回答

0
public static void main(String[] args) { 

     Pt[] point = new Pt[2]; 
     Pt pt1 = new Pt(); 
     pt1.setCoords(0, 0); 
     Pt pt2 = new Pt(); 
     pt2.setCoords(1, 1); 
     point[0] = pt1; 
     point[1] = pt2; 

     getElement(point, 1, 1); // returns element with coords of (1, 1) or null if doesn't exist 

    } 

    public static Pt getElement(Pt[] point, int xCoord, int yCoord) { 
     for (int i = 0; i < point.length; i++) { 
      if (point[i].getX() == xCoord && point[i].getY() == yCoord) { 
       return point[i]; 
      } 
     } 
     return null; 
    } 
+0

您沒有使用「xCoord」和「yCoord」參數。 – Flown

+0

@Flown - 哎呀!更正。 – ferekdoley

+0

我想我應該也可以填充陣列... – ferekdoley

1

你只需要遍歷數組並檢查每個元素。要遍歷數組,您可以使用增強型for循環。

for (Pt pt : point) { 
    if(pt.getX() == 1 && pt.getY() == 1){ 
     //what you want to do with the object... 
     break; 
    } 
} 
相關問題