【问题标题】:How do I use a variable from one method oin another?如何在另一种方法中使用来自一种方法的变量?
【发布时间】:2020-11-18 01:22:15
【问题描述】:

我正在尝试用字母表中的 26 个字母定义一个数组。然后我想在另一种方法中使用数组。如何在shiftLeft 函数中使用arrayEins 变量?提前致谢!

public class VigenereCipher {
    public static void[] dasAlphabet() {
        // char[] arrayEins = new char[26];
        char[] arrayEins;
        for (int i = 97; i < 123; i++) {
            arrayEins = new char[]{(char) i};
        }
    }

    public static void shiftLeft() {

    }

    public static void main(String[] args) {
        dasAlphabet();
        shiftLeft();
    }
}

【问题讨论】:

  • 您需要在一个范围内声明arrayEins,使其在静态方法的主体中可见。将其设为 VigenereCipher 的私有静态字段即可。您还有另一个问题:您能否准确解释一下您认为arrayEins = new char[]{(char) I}; 行的作用?
  • 嘿,我想将arrayEins声明为字母表中的所有字母,从(char)97-122开始,所以我认为我可以使用该行将数字声明为(char ),但现在我知道这只会生成一个长度为 1 的新数组。如何声明我的数组中的所有字母?

标签: java arrays methods


【解决方案1】:

arrayEins 处的数组是dasAlphabet 的本地数组,这意味着它实际上不存在,除非dasAlphabet 正在执行。

需要将数组声明为类的静态成员变量。

但也要注意这段代码是错误的:

        arrayEins = new char[]{(char) i};

每次循环都会创建一个新数组,因此最终结果是一个长度为 1 的数组,其唯一元素的值为 122。

【讨论】:

    猜你喜欢
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2018-08-25
    相关资源
    最近更新 更多