0

我为此使用命令行参数:

public class Pg253E4 {
    public static void main(String[]args) {
        try {
            System.out.println(Average.average(args)); // This part is saying I don't have a method in Average called average(String[] argName)
        } catch(NullPointerException e) {
            System.out.println(e.toString());
        } catch(NumberFormatException e) {
            System.out.println(e.toString());
        } finally {
            System.out.println("Nice job");
        }
    }
}

这是另一个类:

public class Average {
    public static double average(String[] arrayString) throws NullPointerException,NumberFormatException {
        double sum=0;
        double arrayStorage[] = new double[arrayString.length];

        for(int i = 0; i< arrayString.length; i++) {
            arrayStorage[i] = Double.parseDouble(arrayString[i]);
        }
        for(int i = 0; i<arrayString.length; i++) {
            sum += arrayStorage[i];
        }
        return (sum/arrayString.length);
    }
}

我不明白为什么会弹出一个语法错误,说我没有声明或定义类中调用average(String[] argName)的任何方法Average,而我显然这样做了。

4

2 回答 2

1

尝试Average在主类中创建该类型的新对象。为此,请在您的 main 方法中写入以下行:
Average a = new Average();

然后改变你System.out.println(Average.average(args))
System.out.println(a.average(args))

于 2013-06-30T23:44:04.437 回答
0

如果您不使用包,则需要确保Average将其导入您的Pg253E4类:

import Average; // Assuming "Average" is not in a package.

public class Pg253E4
{
    // The rest of your stuff
}

可能最好使用至少一个包:

package yourpackage;

public class Pg253E4
{
    // The rest of your stuff
}

package yourpackage;

public class Average
{
    // The rest of your stuff
}

如果Pg253E4并且Average没有足够的共同点放在同一个包中,那么它们都应该放在自己的包中,在这种情况下,您必须再次Average导入Pg253E4

package yourfirstpackage;

import yoursecondpackage.Average;

public class Pg253E4
{
    // The rest of your stuff
}

package yoursecondpackage;

public class Average
{
    // The rest of your stuff
}
于 2013-06-30T23:48:52.413 回答