Java在方法中访问字符串数组

标签 java scope

我在方法A中有一个字符串数组(变量),它存在于类A中。现在我想访问它并使用 B 类 中的 方法 B 中的另一个字符串数组设置它。 B 类 位于A 类 中。

我是 Java 初学者,因此非常感谢任何帮助。非常感谢。

public class A {
    B myclassb;

    void methodA() {
        String[] myvar;
    }
}

public class B {
    void methodB() {
        // how do I get to A.methodA.myvar?
    }
}

最佳答案

尚不完全清楚您想要实现什么,但无论如何我都会尝试回答。 选项 1:您说过要在嵌套类中的方法 b 中的方法 a 中分配一个变量。这是不可能直接实现的,因为函数变量无法从另一个函数访问,并且在函数完成执行后不再存在。所以你可以将它作为输入参数传输:

public class A {
    public void a(String[] input){
        String[] theArray = input;
    }

    private class B{
        private void b(){
            String[] input = new String[] {"an", "awesome", "Test"};
            a(input);
        }
    }
}

选项 2:使用成员变量:

public class A {
    private String[] theArray;
    public void a(){
        this.theArray = new String[] {"a", "nice", "Test"};
        B bObject = new B();
        //modify value within b():
        bObject.b();

        //or assign it using a return value:
        this.theArray = bObject.b2();
    }

    private class B{
        private void b(){
            theArray = new String[] {"an", "awesome", "Test"};
        }

        private String[] b2(){
            return new String[] {"an", "awesome", "Test"};
        }
    }
}

关于Java在方法中访问字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732962/

相关文章:

java - 如何使用变量声明新的 JComboBox

java - 是否可以通过我的 Java GWT 应用程序验证 Google 帐户?

scope - 在 LilyPond 中定义函数 inside\score

coldfusion - 我应该将实用程序单例组件放在什么范围内?

iphone - 如何将一个 View Controller 中的字符串变量访问到另一个 View Controller

java - 组织小型公用事业功能

java - GWT 客户端工厂 : Isn't this just a big blob/monolith?

java - 如何使用keytool创建证书?

c++ - 访问回调范围之外的变量c++

c - 堆栈和引用传递