Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I pass an array from my main method to another method? I'm having an error with the parameters. Do I use the return value from main? And since the return value from main is an array, should the parameters for the call of main have brackets? Should there be a value between those brackets?

public class arraysAndMethods {

public void printArray(double[] arr) {
    int x = arraysAndMethods.main(double[i] arr);//error with paremeters
    for (int i = 0; i < studGrades.lenght; i++)
        System.out.print(studGrades[i] + " ");
}// end of printArray method

public static double[] main(String args[]){// double array
    java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
    System.out.println("What is the size of the class?");
    int n = input.nextInt();
    double[] arr = new double[n];// declare and initialize array to have n many elements
    for (int i = 0; i < arr.length;i++) {// input grades for each students
        System.out.println("What is the grade of student #" + (i+1));
        arr[i] = input.nextDouble();
    } // end of for loop
    return arr; 
}// end of main method

}// end of class
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
142 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just pass the name, not the type.

int x = arraysAndMethods.main(arr);

EDIT: Besides that, your code shows a few other problems.

  1. main(...) is the entry point to your application. It doesn't make sense to call main(...) from the other method. It should be the other way around.
  2. main(...) HAS TO have the following signature: public static void main(String[] args). You cannot declare it to return an array of double.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...