我有一个方法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
}
答案 0 :(得分:5)
这是一个文字(评论)说明的解释(问题和答案):
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()
方法返回后(如果它被调用)。
建议:将您的数组声明为您的类的属性,将其设置为静态,然后您可以从resultCard
和a()
两种方法中将其称为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"
}