gpt4 book ai didi

java - 关于子类中重写的困惑

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:05 24 4
gpt4 key购买 nike

所以我得到了以下 GradedActivity 类:

 public class GradedActivity
{
private double score; // Numeric score

public void setScore(double s)
{
if (s < 0)
score = 0.0;
else if (s > 100)
score = 100.0;
else
score = s;
}

public double getScore()
{
return score;
}


public char getGrade()
{
char letterGrade;

if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';

return letterGrade;
}
}

我的任务是生成一个构造函数,该构造函数接受点 Obtaned 和 pointsTotal 的值作为参数,初始化它们,并设置相应的分数(获得的分数除以总分数)、获取的分数和总计的访问器和修改器。

这就是我的想法:

public class ProgrammingAssignment extends GradedActivity 
{
public int pointsObtained;
public int pointsTotal;

public ProgrammingAssignment(int p, int t)
{

pointsObtained = p;
pointsTotal = t;
}

public int getPointsObtained()
{
return pointsObtained;
}

public int getPointsTotal()
{
return pointsTotal;
}

public double getScore()
{
return pointsObtained / pointsTotal;
}

public void setPointsObtained(int p)
{
pointsObtained = p;

}

public void setPointsTotal(int t)
{
pointsTotal = t;
}
}

一切编译都没有错误,但在我的测试类中 getScore 没有计算获得的/总计(它返回 0):

 public class PADemo
{
public static void main(String[] args)
{
ProgrammingAssignment p1 = new ProgrammingAssignment(28,30);
GradedActivity p2 = new ProgrammingAssignment(0,30);

System.out.println (p1.getPointsObtained());
System.out.println (p1.getPointsTotal());
System.out.println (p1.getScore());
System.out.println (p1.getGrade());

System.out.println (p2.getScore());
System.out.println (p2.getGrade());

p1.setPointsObtained(25);
p1.setPointsTotal(40);
System.out.println (p1.getScore());
System.out.println (p1.getGrade() == 'F');
}
}

如何使用 getScore() 获取分数(获得的分数/总分数)

测试类返回:

28
30
0.0
F
0.0
F
0.0
正确

最佳答案

从表面上看,解决问题最简单的方法是将 getScore() 更改为:

public double getScore()
{
return (pointsObtained * 100) / pointsTotal;
}

你的代码所做的是给你 0.93 而不是 93,并且当放入整数时 0.93 会被截断为 0(如注释中所指出的)。

关于java - 关于子类中重写的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57704494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com