toString 中的平均成绩
Grade average in toString
我正在为我的 class 做可怕的平均成绩问题并且遇到 运行 很多问题,但这一个似乎是主要问题。我无法将我的方法中计算出的平均值拉到 toString
。这是一种方法:
public void average() {
total = (((quiz1 + quiz2) / 40 * 25) + (midterm / 100 * 35) + (finalExam / 100 * 40));
DecimalFormat dec = new DecimalFormat("#.0");
dec.format(total);
return;
}
我正试图在此处获取它:
public String toString(){
return ("Grade Report:\n" ....+ "Total Score " + total + "\n" ....);
您的平均方法已将 void
声明为其 return 类型。它实际上应该 return 它计算的值:
public String average(){
total = (((quiz1 + quiz2)/40 * 25) + (midterm/100 * 35) + (finalExam/100 * 40));
DecimalFormat dec = new DecimalFormat("#.0");
return dec.format(total);
}
public String toString(){
return ("Grade Report:\n" + average() + "Total Score " + total + "\n" ....);
}
我看到两个错误:
你不是 returning 你的 average
方法的结果,当你 可能 应该而不是存储它变成了一个领域。这很容易修复。
您可能正在除以整数;如果我们可以假设 quiz1
、quiz2
、midterm
和 finalExam
都是 int
,那么您将不会得到浮点结果。
第一个修复很简单:删除 total
字段并将其替换为局部变量。然后,return格式的结果。
String total = ...
return dec.format(total);
接下来,为确保您不除以整数,请在您的商中放置一些小数。
String total = (((quiz1 + quiz2) / 40.0 * 25) + (midterm / 100.0 * 35) + (finalExam / 100.0 * 40));
average
方法不应该设置任何东西 - 它应该只是 return 平均值。然后,您可以在 toString
方法中格式化此数字:
public double average() {
return (((quiz1 + quiz2)/40 * 25) +
(midterm/100 * 35) +
(finalExam/100 * 40));
}
public String toString(){
DecimalFormat dec = new DecimalFormat("#.0");
String averageString = dec.format(average();
return ("The average score is " + averageString); // just an example
}
我正在为我的 class 做可怕的平均成绩问题并且遇到 运行 很多问题,但这一个似乎是主要问题。我无法将我的方法中计算出的平均值拉到 toString
。这是一种方法:
public void average() {
total = (((quiz1 + quiz2) / 40 * 25) + (midterm / 100 * 35) + (finalExam / 100 * 40));
DecimalFormat dec = new DecimalFormat("#.0");
dec.format(total);
return;
}
我正试图在此处获取它:
public String toString(){
return ("Grade Report:\n" ....+ "Total Score " + total + "\n" ....);
您的平均方法已将 void
声明为其 return 类型。它实际上应该 return 它计算的值:
public String average(){
total = (((quiz1 + quiz2)/40 * 25) + (midterm/100 * 35) + (finalExam/100 * 40));
DecimalFormat dec = new DecimalFormat("#.0");
return dec.format(total);
}
public String toString(){
return ("Grade Report:\n" + average() + "Total Score " + total + "\n" ....);
}
我看到两个错误:
你不是 returning 你的
average
方法的结果,当你 可能 应该而不是存储它变成了一个领域。这很容易修复。您可能正在除以整数;如果我们可以假设
quiz1
、quiz2
、midterm
和finalExam
都是int
,那么您将不会得到浮点结果。
第一个修复很简单:删除 total
字段并将其替换为局部变量。然后,return格式的结果。
String total = ...
return dec.format(total);
接下来,为确保您不除以整数,请在您的商中放置一些小数。
String total = (((quiz1 + quiz2) / 40.0 * 25) + (midterm / 100.0 * 35) + (finalExam / 100.0 * 40));
average
方法不应该设置任何东西 - 它应该只是 return 平均值。然后,您可以在 toString
方法中格式化此数字:
public double average() {
return (((quiz1 + quiz2)/40 * 25) +
(midterm/100 * 35) +
(finalExam/100 * 40));
}
public String toString(){
DecimalFormat dec = new DecimalFormat("#.0");
String averageString = dec.format(average();
return ("The average score is " + averageString); // just an example
}