java中 类的其他方法怎么引用main方法中的数组和变量?
时间: 2024-05-11 18:17:49 浏览: 67
如果你想在类的其他方法中引用 main 方法中的数组和变量,你可以采用以下两种方法:
1. 将数组和变量定义为类的静态成员变量,这样其他方法就可以通过类名直接调用。
例如:
```
public class MyClass {
static int[] myArray;
static int myVariable;
public static void main(String[] args) {
myArray = new int[5];
myVariable = 10;
// ...
}
public static void otherMethod() {
int x = myVariable;
// ...
}
}
```
在其他方法中,你可以直接通过 `MyClass.myArray` 和 `MyClass.myVariable` 来引用这些变量。
2. 将数组和变量作为参数传递给其他方法。
例如:
```
public class MyClass {
public static void main(String[] args) {
int[] myArray = new int[5];
int myVariable = 10;
// ...
otherMethod(myArray, myVariable);
}
public static void otherMethod(int[] array, int variable) {
int x = variable;
// ...
}
}
```
在 `main` 方法中,你可以通过将数组和变量作为参数传递给 `otherMethod` 方法来引用它们。
以上是两种常用的方法,你可以根据实际情况选择适合你的方式。
阅读全文
相关推荐


















