Java 将数组从一个方法调用到另一个方法
我有一个方法a,我在其中创建了一个数组。现在我想在另一个方法B中使用数组,我想知道是否有可能在方法B中调用方法A并使用数组,而不是在我创建的每个方法中创建数组Java 将数组从一个方法调用到另一个方法,java,arrays,methods,Java,Arrays,Methods,我有一个方法a,我在其中创建了一个数组。现在我想在另一个方法B中使用数组,我想知道是否有可能在方法B中调用方法A并使用数组,而不是在我创建的每个方法中创建数组 public static void myArray() { String[][] resultCard = new String[][]{ { " ", "A", "B", "C"}, { "Maths", "78", "98","55"},
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
}
下面是一段文字(评论)说明(包括问题和答案):
编辑:
您编辑了问题并包含了代码。在您的代码中,数组不是在方法A中创建的,而是在myArray()
中创建的,并且您不返回它,因此在myArray()
方法返回后(如果调用过它),它将“丢失”
建议:将数组声明为类的属性,使其成为静态的,您可以通过a()
和b()两种方法将其称为resultCard
:
显示部分代码。。。这会详细解释你在说什么。。。不仅是文字,甚至是代码都能解释!!。是的,使用了实例变量(在方法之外声明),或者使用方法返回它。您的标题有点误导(而且没有意义)…不确定您的意思,但我会根据我认为我理解的内容给您一个答案。嗨,Icza,感谢您的代码,但是在实现代码之后,我得到了以下错误:参数resultCard的非法修饰符;在放置私有静态字符串[][]的第一行上只允许使用final。。。如果我删除单词private static,那么错误就消失了。我在void[]上遇到的第二个错误是公共静态void A()行上的无效类型…注意:resultCard
不在任何方法内,它是封闭类的字段。第二:在我发布的代码中没有任何人可以看到void[]
,我不知道你从哪里得到的!
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
}
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"
}