我已经创建了数组,并且在其类之外创建了一个方法来对数组进行排序。它一直说找不到我创建的数组的变量名。当我采用该方法并将其放入与数组相同的类中时,它可以工作,但它违背了我想要实现的目的,有帮助吗?
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter a length for the array: ");
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int randomNumbers[] = new int[x];
for (int index = 0; index < randomNumbers.length; index++)
{
randomNumbers[index] = (int) (Math.random() * 100);
}
for (int index = 0; index < randomNumbers.length; index++)
{
System.out.println(randomNumbers[index]);
}
}
static void sortAscending()
{
Arrays.sort(randomNumbers);
for (int i = 1; i < randomNumbers.length; i++) {
System.out.println("Number: " + randomNumbers[i]);
}
}
最佳答案
由于 randomNumbers
是在 main
方法中声明的,因此其他方法无法访问它。有多种方法可以使数组可以从其他方法访问,例如:
作为参数传递给方法:
static void sortAscending(int[] randomNumbers) { //... }
并像这样从
main
调用sortAscending
调用sortAscending(randomNumbers);
通过字段传递值。但是,我不会使用静态字段,因为所有实例都只有这些字段之一。但是您可以使用类的实例并将值存储在非静态字段中:
publc class MyClass { // declare randomNumbers as field private int[] randomNumbers; public static void main(String[] args) { MyClass o = new MyClass(); o.localMain(args); // you could call sortAscending here like this o.sortAscending(); } // you don't really need to pass args, since you don't use it public void localMain(String[] args) { // TODO code application logic here System.out.println("Enter a length for the array: "); Scanner scan = new Scanner(System.in); int x = scan.nextInt(); // assing new value to field randomNumbers = new int[x]; for (int index = 0; index < randomNumbers.length; index++) { randomNumbers[index] = (int) (Math.random() * 100); } for (int index = 0; index < randomNumbers.length; index++) { System.out.println(randomNumbers[index]); } } void sortAscending() { Arrays.sort(randomNumbers); for (int i = 1; i < randomNumbers.length; i++) { System.out.println("Number: " + randomNumbers[i]); } } }
关于java - 为什么我不能在类之外的方法中使用数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29985240/