【问题标题】:java. help accessing array that is inside a method from another method [duplicate]爪哇。帮助从另一个方法访问方法内部的数组[重复]
【发布时间】:2021-12-17 00:51:38
【问题描述】:

在此我试图让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+" ");
  }

【问题讨论】:

  • 将其存储在类的字段中,或将其作为参数传递给您的方法
  • 了解范围

标签: java arrays methods


【解决方案1】:

为每个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 + " ");
    }
}

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

【讨论】:

    【解决方案2】:
    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")
    

    【讨论】:

      猜你喜欢
      • 2012-01-19
      • 2021-01-10
      • 2016-01-21
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 2011-03-27
      相关资源
      最近更新 更多