首页 > 解决方案 > 如何访问从方法传递的数组以便在主方法中重新排列它

问题描述

public class ICT_Questions_34 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the Index of Numbers");
        int n = input.nextInt();
        RandomNumber(n);// It returns n number of 2 digit numbers at here. 

System.out.println(myList.length);
System.out.println(myList[2]);
// there seems to be a problem here as the method I called prior this statements is as if it isn't working. What's the problem
    }

    public static int[] RandomNumber(int n) {
        if (n < 0) {
            System.out.println("PLEASE Enter Positive Number!");
        }
        int[] myList = new int[n];
        for (int i = 0; i < n; i++) {

            int Values = (int) ((90 * Math.random()) + 10);
            System.out.print(Values + "\t");
            for (int j = i; j < n; j++) {

                myList[j] = Values;

            }

        }
        return myList;
    }

}

标签: java

解决方案


的范围是int[] myList该方法的本地范围,public static int[] RandomNumber(int n)因此无法在该方法之外访问它。

但是您正在返回数组,因此您可以像代码一样访问该main方法。int[] myList = RandomNumber(n);

public class ICT_Questions_34 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the Index of Numbers");
        int n = input.nextInt();
        int[] myList = RandomNumber(n);// It returns n number of 2 digit numbers at here. 

        System.out.println(myList.length);
        System.out.println(myList[2]);
        // there seems to be a problem here as the method I called prior this statements is as if it isn't working. What's the problem
    }

    public static int[] RandomNumber(int n) {
        if (n < 0) {
            System.out.println("PLEASE Enter Positive Number!");
        }
        int[] myList = new int[n];
        for (int i = 0; i < n; i++) {

            int Values = (int) ((90 * Math.random()) + 10);
            System.out.print(Values + "\t");
            for (int j = i; j < n; j++) {

                myList[j] = Values;

            }

        }
        return myList;
    }

}

推荐阅读