为什么我不能在类外的方法中使用数组?

时间:2015-05-01 10:26:20

标签: java arrays sorting methods syntax

我创建了数组,在类的外部我创建了一个对数组进行排序的方法。它一直说它找不到我所制造的数组的变量名。当我接受这个方法并将它放入与它所使用的数组相同的类时它会失败我想要达到的目的,帮助吗?

/**
 * @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]);
        }
    }  

1 个答案:

答案 0 :(得分:2)

由于randomNumbers方法中声明了main,因此其他方法无法访问它。有几种方法可以从其他方法访问数组,例如:

  1. 将参数传递给方法:

    static void sortAscending(int[] randomNumbers) {
        //...
    }
    

    并拨打sortAscending来自main的电话

    sortAscending(randomNumbers);
    
  2. 通过字段传递值。但是,我不会使用静态字段,因为所有实例中只有一个字段。但是您可以使用类的实例并将值存储在非静态字段中:

    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]);
            }
        }  
    
    }
    
相关问题