New*_*bie -11 java arrays methods
我有一个方法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
}
Run Code Online (Sandbox Code Playgroud)
这是一个文字(评论)说明的解释(问题和答案):
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
}
Run Code Online (Sandbox Code Playgroud)
编辑:
您编辑了问题并包含了代码.在你的代码中,数组不是在方法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"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3518 次 |
| 最近记录: |