【问题标题】:Call an array from one method to another method [closed]将数组从一种方法调用到另一种方法[关闭]
【发布时间】:2014-10-18 11:47:54
【问题描述】:

我有一个方法 A,我在其中创建了一个数组。现在我想在另一个方法 B 中使用数组,想知道是否有可能在方法 B 中调用方法 A 并使用数组而不是在我创建的每个方法中创建数组。

public static void myArray() {
    String[][] resultCard =  new String[][]{ 
                { " ", "A", "B", "C"},
                { "Maths", "78", "98","55"}, 
                { "Physics", "55", "65", "88"}, 
                { "Java", "73", "66", "69"},
             };
}

public static void A() {
    //Not sure how I can include the array (myArray) here   
}

public static void B() {
    //Not sure how I can include the array (myArray) here   
}

【问题讨论】:

  • 显示部分代码...这将详细解释您所说的内容...不仅文字,甚至代码都可以解释!
  • 是的,使用了实例变量(在方法之外声明),或者使用方法返回。
  • 你的标题有点误导(而且毫无意义)......
  • 不确定你的意思,但我会根据我认为我理解的内容给你一个答案。

标签: java arrays methods


【解决方案1】:

这是一个文字(评论)图解说明(问题答案):

public Object[] methodA() {
    // We are method A
    // In which we create an array
    Object[] someArrayCreatedInMethodA = new Object[10];
    // And we can returned someArrayCreatedInMethodA
    return someArrayCreatedInMethodA;
}

public void methodB() {
    // Here we are inside another method B
    // And we want to use the array
    // And there is a possibility that we can call the method A inside method B
    Object[] someArrayCreatedAndReturnedByMethodA = methodA();
    // And we have the array created in method A
    // And we can use it here (in method B)
    // Without creating it in method B again
}

编辑:

您编辑了您的问题并包含了您的代码。在您的代码中,数组不是在方法 A 中创建的,而是在 myArray() 中创建的,并且您没有返回它,因此在 myArray() 方法返回后它“丢失”了(如果曾经调用过)。

建议:将数组声明为类的属性,将其设为静态,您可以在a()b() 两种方法中简单地将其称为resultCard

private static String[][] resultCard = new String[][] {
    { " ", "A", "B", "C"},
    { "Maths", "78", "98","55"},
    { "Physics", "55", "65", "88"},
    { "Java", "73", "66", "69"},
};

public static void A() {
    // "Not sure how I can include the array (myArray) here"
    // You can access it and work with it simply by using its name:
    System.out.println(resultCard[3][0]); // Prints "Java"
    resultCard[3][0] = "Easy";
    System.out.println(resultCard[3][0]); // Prints "Easy"
}

【讨论】:

  • 嗨 Icza,感谢您的代码,但在执行代码后,我收到以下错误:参数 resultCard 的非法修饰符;在您放置 private static String[][]... 的第一行只允许 final ...我在 void[] 处遇到的第二个错误是 public static void A() 行上的无效类型...
  • 注意:resultCard 不是在任何方法中,它是封闭类的一个字段。第二:在我发布的代码中,无论如何都没有void[],我不知道你从哪里得到的!
猜你喜欢
  • 2013-02-10
  • 1970-01-01
  • 2016-02-11
  • 2013-01-29
  • 1970-01-01
  • 2011-07-05
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多