2015-01-11 57 views
1

如果有一個陣列,例如:如何從一個數組中獲取一個值用於另一個類中?

//.... 
int[] anArray; 
anArray = new int[3]; 
anArray[0] = new otherClassWConst(x, y , z); 
anArray[1] = new otherClassWConst(x, y , z); 
anArray[2] = new otherClassWConst(x, y , z); 
//.... 

隨着x和y和z都存在不同的值的與所述其他的x,y和z的從所述陣列中的其他對象的值。 (這有意義嗎?就像anArray [0]中的x​​的值與anArray [2]中的值不同一樣)。 注意:有另一個類的構造函數需要這些參數,我不確定這是否重要

我如何在不同的類中獲取其中一個參數的值(例如, y的值)在每個數組值中。如果有,我可以得到Y的所有三個值的方法,以便我可以將它們一起添加到另一個類中?

例如

//code attaining only the y values of the array 
overallValueOfY = Y + Y + Y; // or something of that nature 
//life continues over here. 

請告訴我,如果有任何不明白,我那麼努力解釋。感謝您的考慮。

+0

顯示你的班級結構。 –

回答

0

OtherClassConst需要提供get方法吧:

public class OtherClassConst { 
    private int x; 
    private int y; 
    private int x; 

    public (int x, int y, int z) { 
     this.x = x; 
     this.y = y; 
     this.z = z; 
    } 

    public int getY() { 
     return y; 
    } 
    /* Same concept for getX() and getZ() */ 
} 

然後,類可以調用它:

int sumY = 0; 
for (OtherClassConst c : myArray) { 
    sumY += c.getY(); 
} 
+0

我非常愛你,我真的希望這可以工作<3333 –

+0

或者,你可以用'public final int'而不是'private int'變量來使用不可變的對象,並使用'cy'而不是'c.getY()' 。 –

0

首先,你的磁盤陣列不會,除非你的新類工作延伸詮釋,我只是想確保你知道這一點。現在

,所有你需要做的就是在新類中創建一個int varriable

int x; 
int y; 
int z; 

並將它們等於什麼放在構造函數。然後創建一個返回值

public int getX(){ 
    return this.x; 
} 
public int getY(){ 
    return this.Y; 
} 
public int getZ(){ 
    return this.Z; 
} 
+0

順便說一下,如果OP不知道,你不能子類int,任何原語,甚至整數(這是最後)。只要確保:-) –

+0

哦!看到我不知道!然後他的陣列不會工作lol – MagnusCaligo

+0

子類化是什麼意思? –

0

您需要爲您的用X,Y和Z的實例變量其他類中創建POJO,然後用Y的,你可以得到的值setter方法的新方法。遍歷它們以獲得值的總和。

0

如果其他OtherClassgetY方法返回一個整數,那麼你可以使用下面來總結他們:

Arrays.stream(anArray).mapToInt(OtherClass::getY).sum(); 

這是值得去使用,以使用流而不是循環。

相關問題