Java方法调用数组 [英] Java Method Call Array
问题描述
如何将数组从主方法传递给另一个方法?我的参数有误.我是否使用main的返回值?而且由于main的返回值是一个数组,所以main调用的参数是否应该带有方括号?这些括号之间应该有一个值吗?
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
推荐答案
这整件事没有多大意义.如果希望将此作为Java程序的main
方法,则此方法将无效,因为main
方法必须具有void
返回类型.无论如何,您在这里有语法错误:
This whole thing doesn't make much sense. If you're hoping to have this as the main
method of a Java program, this won't work because the main
method must have a void
return type. Regardless, you have a syntax error here:
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
应该是
int x = arraysAndMethods.main(arr);//error with paremeters
,因为该变量已被声明.我不确定您要使用double[i]
做什么,但是该语法更像是声明,即
as the variable has already been declared. I'm not sure what you were trying to do with double[i]
, but that syntax is more like a declaration, i.e.
double[] someArrayName = new double[5];
这篇关于Java方法调用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!