从一种方法调用数组到另一种方法 [英] Call an array from one method to another method
问题描述
我有一个方法 A,我在其中创建了一个数组.现在我想在另一个方法 B 中使用该数组,并且想知道是否有可能在方法 B 中调用方法 A 并使用该数组而不是在我创建的每个方法中创建该数组.
I have a method A in which I have created an array. Now I want to use the array in another method B and was wondering if there is any possibility that I can call the method A inside method B and use the array instead of creating the array in each and every method I create.
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
}
推荐答案
这是一个文字(评论)说明说明(问题和答案):>
Here's a text (comment) illustrated explanation (both the question and the answer):
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()
方法返回(如果它被调用过).
You edited your question and included your code. In your code the array is not created in method A but in the myArray()
, and you don't return it, so it is "lost" after the myArray()
method returns (if it is ever called).
建议:将您的数组声明为您的类的一个属性,使其成为静态的,您可以在 a()
和 方法中将其简单地称为
:resultCard
代码>b()
Suggestion: declare your array as an attribute of your class, make it static, and you can simply refer to it as resultCard
from both methods a()
and b()
:
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"
}
这篇关于从一种方法调用数组到另一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!