在循环内定义的Java变量似乎无法在循环外识别

在循环内定义的Java变量似乎无法在循环外识别

本文介绍了在循环内定义的Java变量似乎无法在循环外识别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段令人困惑的代码.我在if/else语句中定义了一个整数数组,因为该数组的长度取决于该方法的2个输入的长度.我的问题是,在if/else语句之外,变量定义似乎丢失了.

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 method. My problem is that outside the if/else statement, the variable definition seems to be lost.

import java.util.Arrays;

public class test {

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

我得到的错误是在语句String result = Arrays.toString(output);上,Eclipse告诉我output无法解析为变量.

The error I get is on the statement String result = Arrays.toString(output); where Eclipse tells me that output cannot be resolved to a variable.

...并且顺便说一句,是的,我知道这不是添加两个整数数组的方法-我从更复杂的代码中简化了此过程以演示问题!

...and by the way, yes, I know that this is not the way to add two integer arrays -- I reduced this from more complex code to demonstrate the problem!

推荐答案

if语句之前定义output.像这样:

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;
}

if语句中声明output时,它仅具有该块作用域.

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

这篇关于在循环内定义的Java变量似乎无法在循环外识别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:08