【问题标题】:Error in method declaration方法声明错误
【发布时间】:2014-01-10 00:13:30
【问题描述】:
我正在编写一个程序来查找数组的平均值以及大于该平均值的数字。我试图用一种方法来写这一切。但是,我在方法声明方面遇到问题,因为我被告知我所拥有的是非法表达式。我做错了什么?
public class Average {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
public double average(double[] number) {
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
double[] smallerList = new double[10];
int averageIndex = 0;
int largerIndex = 0;
int smallerIndex = 0;
谢谢
【问题讨论】:
标签:
java
arrays
methods
declaration
average
【解决方案1】:
您不应该在方法中声明方法。
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
}
public double average(double[] number) {
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
double[] smallerList = new double[10];
int averageIndex = 0;
int largerIndex = 0;
int smallerIndex = 0;
... More code ...
}
如上所示,关闭主方法块,然后声明一个新方法。
【解决方案3】:
Note: A method is like passing control to some other person which will do certain types of action,by declaring it inside a method it's like calling the same method again and again
In case of Java it has main method and all utility methods to do things for you.In your case
public class Average(){
// your main function starts here
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// you can ideally call your average method from here
// Your method definition and declaration shouldn't be here
}//end of main method
public double average(double[] number) {
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
double[] smallerList = new double[10];
int averageIndex = 0;
int largerIndex = 0;
int smallerIndex = 0;
}
}//Closing your class Average