为什么我的方法给我空值?

时间:2013-11-19 06:14:52

标签: java arrays loops for-loop methods

我不明白为什么我会收到这样的价值。此方法直接依赖于数组,而间接依赖于另外两个数组。它们都填充了相似数量的步骤,但填充它们的方法各不相同。有些从顶部变为零,而其他从零开始。如果这没有意义,我可以详细说明

阿尔法值从上到下填充,而依赖于从下到上填充的另一个阵列。这是允许的吗?

blic class ItrDensityGrid {

public double itrrho [ ];           // defines an a array of adjusted densities

double b = InitialConditions.bmod;  

// Iterating grid of adjusted densities 

public ItrDensityGrid ( int shells , double radius , double mass , double bmod ) {      // Density constructor with inputs

    GravityGrid gg = new GravityGrid ( shells , radius , mass , bmod );             // Pulls gravity array for use, will change each iteration  

    itrrho = new double [ shells + 1 ];                                         // Defines number of elements in array as shells with steps of 1

    for( int k = shells ; k >= 1 ; k -- ){                                  // for loop fills array from top shell down

    itrrho[ k ] = ( itrrho [ k ] * ( 1 + ( gg . alpha [ k ] * ( 1.0 / 2 )))*( 1 / ( 1 - (( gg.alpha[ k ]) * ( 1.0 / 2 )))));   // defines elements form top down

        System.out.println("The adjusted density at shell " + k + " is " + itrrho[k]);

        }
    }

public double itrrho( int k ){

    return( itrrho[ k ] );

    }
}

2 个答案:

答案 0 :(得分:3)

itrrho[ k ] = ( itrrho [ k ] *  ( 1 + ( gg . alpha [ k ] * ( 1.0 / 2 )))*( 1 / ( 1 - (( gg.alpha[ k ]) * ( 1.0 / 2 ))))););

此处itrrho[k] 未初始化因此itrrho的每个元素都将为0.0

所以itrrho [ k ] * ( 1 + ( gg . alpha [ k ] * ( 1.0 / 2 )))*( 1 / ( 1 - (( gg.alpha[ k ]) * ( 1.0 / 2 )))))

将是0.0 * ( 1 + ( gg . alpha [ k ] * ( 1.0 / 2 )))*( 1 / ( 1 - (( gg.alpha[ k ]) * ( 1.0 / 2 )))))

因此你得到0.0

new double[shels+1];

之后执行此类操作
for(int i=0;i<itrrho.length;i++){
    itrrho[i]=1.0; //initialization
}

然后看结果

答案 1 :(得分:0)

您需要实例化该类,否则不会填充该数组。

public class TestItrDensityGrid{
    public static void main(String[] args){
        ItrDensityGrid grid = new ItrDensityGrid ( 5 , 10.0 , 10.0 , 5.0 );

        System.out.println(grid.itrrho( 5 ));
    }
}