我正在通过构造函数传递一个字符串,并将其值赋给一个 Grade 类型的对象类变量。我知道这很简单,但我无法弄清楚如何完成这项工作。我不能修改变量或构造函数参数,只能实现构造函数。
我查看了 string 中的方法,但在一小时后无法弄清楚该怎么做。类型转换/转换/idk
public class Course
{
private String courseNumber;
private int numberOfCredits;
private Grade gradeReceived;
private String termWhenTaken;
/**
* The value for the courseNumber instance variable is converted to uppercase.
* The numberOfCredits instance variable is set to the credits passed as a parameter if it's 0 or more.
* Otherwise, it gets set to 0.
*/
public Course(String course, int credits, String grade, String term)
{ courseNumber = course.toUpperCase();
numberOfCredits = credits;
termWhenTaken = term;
gradeReceived = grade; <-----problem here mismatched data types obviously
}
最佳答案
您不能将类型 A 的对象分配给类型 B 的引用变量(除非 A 是 B 的子类)。您不能将 String
分配给 Grade
。
您需要使用 String
创建一个 Grade
:
gradeReceived = new Grade(grade);
new
运算符调用构造函数 public Grade(String grade)
并返回一个新的 Grade
对象。
关于java - 构造函数和不同的数据类型令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18857768/