我正在使用命令行参数:
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
的方法,当我明确这样做时。
答案 0 :(得分:1)
尝试在主类中创建Average
类型的新对象。为此,请在主方法上写下以下行:
Average a = new Average();
然后将System.out.println(Average.average(args))
更改为
System.out.println(a.average(args))
答案 1 :(得分: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
没有足够的共同点在同一个包中,那么它们都应该放在自己的包中,在这种情况下你必须导入{{1再次进入Average
:
Pg253E4