繁体   English   中英

爪哇。 帮助从另一个方法访问一个方法内的数组

[英]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 + " ";
  }

调用一个方法并让它返回一个值。 您必须声明数据类型。 在这种情况下,它是一个字符串。

公共字符串

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

称呼(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 + " ");
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM