Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

Java Method Call Array

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

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...