如何在每次迭代后在Array中存储值?

时间:2014-11-21 16:31:35

标签: java arrays

考虑以下情况:

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类中的数学运算是在主程序中的forloop上执行的,我想要实现的是我想在每次迭代后将存储在A类中计算的变量的值存入Array b。 最后我希望我的输出看起来像这样:

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

2 个答案:

答案 0 :(得分: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();
        }
    }
}

答案 1 :(得分: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.