Java variable defined inside a loop doesn't seem to be recognized outside the loop?

后端 未结 4 1285
北荒
北荒 2021-01-20 10:54

I have a section of code that is puzzling me. I define an integer array inside an if/else statement because the length of the array depends on the length of 2 inputs to the

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-20 11:18

    Define output before if statement. Like this:

    int[] output;
    int L1 = arg1.length;
    int L2 = arg2.length;
    if (L1 > L2) {
        output = new int[L2];
        for (int i = 0; i < L2; i++) {
            output[i] = arg1[i] + arg2[i];
        }
    } else {
        output = new int[L1];
        for (int i = 0; i < L2; i++) {
            output[i] = arg1[i] + arg1[i];
        }
    }
    String result = Arrays.toString(output);
    return result;
    }
    

    When you declared output inside the if statement it simply had only that block scope.

提交回复
热议问题