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

后端 未结 4 1286
北荒
北荒 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:12

    Well, you have already got the solution, but I would like to point out that, you can reduce your methods, to avoid duplicating codes, which you are currently doing.

    You can make use of conditional operators to create the array according to the result of L1 > L2. And rather than iterating till L1 or L2, you should iterate till the length of array output.

    So, you can try using the below code: -

    public String addArrays(int [] arg1, int [] arg2) {
        int L1 = arg1.length;
        int L2 = arg2.length;
    
        int[] output = L1 > L2 ? new int[L2]: new int[L1];
    
        for (int i = 0; i < output.length; i++) {
            output[i] = arg1[i] + arg2[i];
        }
    
        return Arrays.toString(output);
    }
    

    And please follow Java Naming Conventions. Method name should start with lowercase alphabets.

提交回复
热议问题