我试图通过调用在类中创建的方法来完成我的项目。我收到一个错误“类中的构造函数无法应用于给定类型。
这是我的主要
public static void main(String[] args) {
double[] grades = {98.7, 77.9, 90, 83, 67, 33, 81, 90 };
HomeworkGrades cls = new HomeworkGrades();
这是我的课程
public class HomeworkGrades {
private double[] grades;
double [] HWgrades = { 1, 2, 3, 4, 5, 6, 7, 8};
public HomeworkGrades(double [] gradesEarned)
{
grades= gradesEarned;
for (int i =0; i<gradesEarned.length;i++)
HWgrades =gradesEarned;
}
public double calcAverage()
{
int sum =0;
for(int i =0; i<HWgrades.length; i++)
{
sum = (int) (sum + HWgrades[i]);
}
double average = sum / (double)HWgrades.length;
return average;
}
public static double calcLowestGrade(double[]a, double total)
{
double temp;
double size;
double array[] = { 1, 2, 3, 4, 5, 6, 7, 8};
size = array.length;
for (int i =0; i <size; i++)
{
for(int j=i+1;j<size;j++)
{
if(array[i]>array[j])
{
temp=array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("Lowest grade is " + array[0]);
return array[0];
}
}
答案 0 :(得分:2)
您共享的构造函数使用double[]
。似乎您忘记了传递创建的grades
数组:
double[] grades = {98.7, 77.9, 90, 83, 67, 33, 81, 90 };
HomeworkGrades cls = new HomeworkGrades(grades);
答案 1 :(得分:1)
您忘记为new HomeworkGrades()
实例设置参数。
因此
double[] grades = {98.7, 77.9, 90, 83, 67, 33, 81, 90 };
HomeworkGrades cls = new HomeworkGrades();
应该是
double[] grades = {98.7, 77.9, 90, 83, 67, 33, 81, 90 };
HomeworkGrades cls = new HomeworkGrades(grades);
此外...您在初始化HomeworkGrades时正在做一些疯狂的事情...
这将很好地工作:
double[] HWgrades;
public HomeworkGrades(double [] gradesEarned) {
HWgrades =gradesEarned;
}
您甚至都没有使用private double[] grades;
,也不必设置数组array.length来获得最后的数组。只需做一次。
编辑 为了打印您的Average或您想要从实例中获取的任何内容,只需获取double并将其打印在System.out.println()
中 public static void main(String[] args) {
double[] grades = {98.7, 77.9, 90, 83, 67, 33, 81, 90};
HomeworkGrades cls = new HomeworkGrades(grades);
System.out.println("Average: " + cls.calcAverage());
}
EDIT2 您获得最低成绩的功能很奇怪...仅使用此代替即可:
public double calcLowestGrade() {
double lowest = Double.MAX_VALUE;
for (double d : HWgrades) {
if (d < lowest) {
lowest = d;
}
}
return lowest;
}
一个错误是您使函数静态化,因此无法获取HWgrades数组。此外,您不必创建新的数组,因为您已经在开始时就为对象提供了该数组。