【问题标题】:How to pass an array from inside a loop to outside the loop in java如何在java中将数组从循环内部传递到循环外部
【发布时间】:2018-05-24 11:59:13
【问题描述】:

所以我正在玩这个程序,如下所示,我想知道如何在循环中修改数组的元素,然后在循环外传递相同的修改数组(如numbers2[count] = numbers4[l] 所示)。当我运行此代码段时,max(numbers2) 指的是我在开头实例化的数组,而不是 if 语句中修改后的数组。知道循环内对象/变量的范围仅在循环内可见,我将如何去做?请在下面给出此代码段的答案。 (Numbers4 是长度为 7 的字符串数组,numbers2 是长度为 3 的字符串数组)。例如,如果我在数组 numbers2 中有一个数组 [9, 7, 10],然后在数组 number4 中有另一个数组 [3, 8, 4, 5, 6, 4, 9],我想将 3 从numbers4 到 numbers2 的第一个索引,导致 [9, 3, 10],我的 if 语句会传递这个特定的数组,还是传递 [9, 7, 10]?

              for(int l = 0; l < numbers4.length; l++) {
                int maxNum2 = max(numbers2);
                if(l % 2 == 0 && l < numbers4.length - 1) {
                    numbers2[count] = numbers4[l];
                    maxNum2 = max(numbers2);
                    int card = Integer.parseInt(numbers4[l + 1]);
                    if(card == 10) {
                        total = total - 10;
                    }else if(card == 11) {
                        total = total + 11;
                    }else if(card == 12) {
                        total = total + 12;
                    }else if(card == 13) {
                        total = total + 13;
                    }else if(card == 14) {
                        if(total < 86) {
                            total = total + 14;
                        }else {
                            total = total + 1;
                        }
                    }else if(card == 9) {
                        total = total + 0;
                    }else {
                        total = total + card;
                    }
                } 

【问题讨论】:

    标签: java arrays scope


    【解决方案1】:

    变量的范围取决于它的声明。如果您在循环外声明一个 Array 变量并在循环内对其进行变异,那么它将在外部范围内可见。内部范围内没有创建新变量。

    由于 numbers2 和 numbers4 没有在循环内声明,它们必须在外部范围内声明。因此,您的 Array 元素突变将在该范围内可见。

    【讨论】:

    • 因此,如果我在数组 numbers2 中有一个数组 [9, 7, 10],然后在数组 number4 中有另一个数组 [3, 8, 4, 5, 6, 4, 9],我想将 numbers4 中的 3 存储到 numbers2 的第一个索引中,结果为 [9, 3, 10],我的 if 语句会传递这个特定的数组,还是传递 [9, 7, 10]?
    • 它会改变数组的内容。最后,numbers2 在声明的范围内的值将是 [9, 3, 10]。
    • 但是在修改numbers2之后程序迭代for循环后,当它调用int maxNum2 = max(numbers2); ,不会是指原始的实例化数组吗?
    • 你正在改变数组。如果我有一套抽屉,我可以改变抽屉里的东西,它们仍然是原来的一套抽屉,但内容不同。
    【解决方案2】:

    通过 numbers2[count] = numbers4[l] 你实际上是在修改你的 numbers2 数组,所以你不需要在循环之外传递它

    【讨论】:

    • 因此,如果我在数组 numbers2 中有一个数组 [9, 7, 10],然后在数组 number4 中有另一个数组 [3, 8, 4, 5, 6, 4, 9],我想将 numbers4 中的 3 存储到 numbers2 的第一个索引中,结果为 [9, 3, 10],我的 if 语句会传递这个特定的数组,还是传递 [9, 7, 10]?
    • numbers2 是对您的数组的引用,因此无论您调用numbers2[count] = something,您都可以修改该数组。它不依赖于块:正如@Josh 提到的,如果您的变量在块外声明,您可以从所有嵌套块访问它
    猜你喜欢
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2020-02-20
    相关资源
    最近更新 更多