当数组超出所需范围时返回null

时间:2019-01-15 14:01:18

标签: java arrays output

说我有一个产生数组的函数:

static long[] solveEquationB(int x, int j) 
{  
    long[] e = new long[j];
    for (int i = 1; i < j; i++)
    {
       x = 1.0*x/(2.0) + 3 ;
       e[i] = x;
    }
    return e;
}

null时如何获得输出以产生j < 0

2 个答案:

答案 0 :(得分:1)

在创建数组之前测试j

static long [] solveEquationB (int x, int j) 
{  
    long[] e = null;
    if (j >= 0) { // or perhaps > 0 if you don't want to return an empty array
        e = new long[j];
        for (int i = 1; i < j; i++)
        {
            x = 1.0*x/(2.0) + 3 ;
            e[i] = x;
        }
    }
    return e;
}

答案 1 :(得分:0)

您只需在上述代码中添加一行作为三元运算符检查即可。这是修改后的代码:

static long[] solveEquationB(int x, int j) {  
     long[] e = j > 0? new long[j]: null;
     for (int i = 1; i < j; i++) {
        x = 1.0*x/(2.0) + 3 ;
        e[i] = x;
     }

     return e;
 }