方法声明出错

时间:2014-01-10 00:13:30

标签: java arrays methods declaration average

我正在编写一个程序来查找数组的平均值以及大于该平均值的数字。我试图在一个方法中写这一切。但是,我遇到了方法声明的问题,因为我被告知我所拥有的是非法表达。我做错了什么?

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;

谢谢

3 个答案:

答案 0 :(得分:0)

您的代码片段缺少main函数的右大括号。

答案 1 :(得分:0)

你不应该在方法中声明一个方法。

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 ...
}

如上所示,关闭主方法块,然后声明一个新方法。

答案 2 :(得分:0)

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