2014-11-21 144 views
-1

考慮下面的情景:正在通過在主程序中一個for循環執行如何在每次迭代後將值存儲在數組中?

Public Class A { 
..... 
static void DoSomething(){ 
    int a=some mathematical operation; 
    int b[10]; 
    } 
} 

Public Class B{ 
.... 
public static void main(String[] args) 
{ 
for(int i=0;i<10;i++){ 
A.DoSomething; 
} 
} 
} 

在這裏,在A級數學運算,我想要實現的是,我要存儲在計算的變量存在的價值每次迭代到數組b後的A類b。 最後,我想我的輸出看起來像這樣:

b[10]=[iteration1value iteration2value......iteration10value] 

回答

1

給一個返回類型DoSomething()和返回值:

Public Class A { 
    ..... 
    public static int DoSomething(){ 
     int a = someMathematicalOperation(); 
     return a;  
    } 
} 

這裏創建b陣列和更新的價值,你循環。

Public Class B{ 
    .... 
    public static void main(String[] args) 
    { 
     int[] b = new int[10]; 
     for(int i=0;i<10;i++){ 
      b[i] = A.DoSomething(); 
     } 
    } 
} 
+0

不知道爲什麼,但這給了我一個空指針異常。 – 2014-11-21 18:03:29

+0

它在哪裏給你?哪條線?你可以在開場白中更新的代碼中進行編輯嗎? – 2014-11-21 18:17:11

+0

那麼現在就解決了,我用你的邏輯,而是使用ArrayLists。謝謝。 – 2014-11-21 18:21:02

0

不確定您是否勾畫出正確的結構。對我來說最有意義的是

1) Class A has non-static, private function called "doSomething()" which returns a result. 
2) Class B has a non-static variable which holds the array. 
3) In "main", instantiate both class A and class B. 
4) Still in main, call a.doSomething() to retrieve the result of the operation. 
5) Take the result of the operation and put it into the array held by B.