java。帮助从另一个方法访问方法内部的数组

java. help accessing array that is inside a method from another method

在此我尝试获取 salutations() 方法来输出在 initialize() 方法中创建的数组。

我收到的错误只是告诉我当我需要它在另一个方法中时为数组创建一个局部变量。

public void initialize() {
String[] salutations = new String[]{"greetings", "hello", "good afternoon"};
String[] verses = new String[]{"we hope you are having a good Christmas", "we wish you a merry x-mas", "we wish you a good new year"};
String[] closing = new String[]{"", "b", "c"};
}
public  void salutations(){
    int i=1;
     String x;
    x=(String)Array.get(salutations, i);
     System.out.println(+x+" ");
  }
public String salutations(int i){
     String x = salutations[i].toString;
     return x + " ";
  }

调用一个方法并赋予它return一个值。您必须声明数据类型。在本例中,它是一个字符串。

public String

要将值传递给方法,您必须声明数据类型并为其指定变量名

salutations(int i)

放在一起看起来像:

public String salutations(int i)

现在你可以通过传入一个int来调用方法了。

System.out.println(salutations(1) + "Bob")

为每个 String[] 创建字段并在其他方法中引用它们:

public class MyClass {
    private String[] salutations;
    private String[] verses;
    private String[] closing;

    public void initialize() {
        salutations = new String[]{"greetings", "hello", "good afternoon"};
        verses = new String[]{"we hope you are having a good Christmas", "we wish you a merry x-mas", "we wish you a good new year"};
        closing = new String[]{"", "b", "c"};
    }

    public void salutations() {
        int i = 1;
        String x;
        x = salutations[i];
        System.out.println(x + " ");
    }
}

其他较小的语法错误已更正。