调用Java主要方法 [英] Java Main Method Called
问题描述
我可以以及如何从Java中的另一个方法调用main方法?请使用以下代码进行解释:
Can I and how could I call the main method from another method in Java? Please explain using the code below:
public class arraysAndMethods {
public void printArray(double[] arr) {
int x = public arraysAndMethods.main(int[] studGrades);
// pass array in main mehthod to other methods
//int a=main(args[]);
for (int i = 0; i < studGrades.lenght; i++)
System.out.print(studGrades[i] + " ");
}// end of printArray method
public static void main(String args[]){
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 studGrades[] = new double[n];
for (int i = 0; i < studGrades.length;i++) {
System.out.println("What is the grade of student #" + (i+1));
studGrades[i] = input.nextDouble();
} // end of for loop
}// end of main method
}//end of class
编辑后:
除了传递参数外,我已经弄清楚了.我是否使用main的返回值?而且由于main的返回值是一个数组,所以main调用的参数是否应该带有方括号?这些括号之间应该有一个值吗?
I've figured it out except for the passing in arguments. 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
推荐答案
从另一种方法调用main方法通常被认为是不好的编程习惯.这可能会导致出现一系列问题,例如无限循环,无限递归等.您的主要方法应包括程序需要操作的高级功能,通常希望它尽可能简单.作为一种很好的检查"方式,请问自己是否可以将此功能制成自己的单独方法?如果是这样,那为什么不这样做呢?然后,如果您需要再次拨打该电话,则可以使用单独的方法进行操作.
It is generally considered bad programming practice to call the main method from another method. This can lead to a whole list of problems such as infinite loops, infinite recursion, etc. Your main method should include high level functionality that your program needs to operate, you generally want it to be as simple as you can keep it. As a good kind of "check" ask yourself can I make this functionality into its own separate method? If so then why not do that? Then if you ever need to make that call again, you have a separate method to do so.
这篇关于调用Java主要方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!