我在构造函数中传递一个字符串,并将其值赋给Grade类型的对象类变量。我知道这很简单,但我无法弄清楚这项工作。我无法修改变量或构造函数参数,只能实现构造函数。
我查看了字符串中的方法,但一小时后无法弄清楚要做什么。铸造/转换/ 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
}
答案 0 :(得分:1)
您不能将类型A的对象分配给类型B的引用变量(除非A是B的子类)。您无法将String
分配给Grade
。
您需要使用Grade
:
String
gradeReceived = new Grade(grade);
new
运算符调用构造函数public Grade(String grade)
并返回一个新的Grade
对象。
答案 1 :(得分:0)
您需要某种转换器或映射来将String值(例如,“6th”)转换为Grade对象。这样的事情可以让你开始:
public Course(String course, int credits, String grade, String term) {
...
gradeReceived = convertGradeStringToGrade(grade);
...
}
private Grade convertGradeStringToGrade(String gradeStr) {
if ("A".equals(gradeStr)) {
return new Grade("A");
} else if ("B".equals(gradeStr)) {
return new Grade("B");
} else if ... etc
} else {
// do something (throw an exception? return null?) if the string doesn't match a known grade
}
}
或者你可以做一些像
这样的事情public Course(String course, int credits, String grade, String term) {
...
gradeReceived = new Grade(grade);
...
}
如果没有任何转换要做。
您也可以为成绩对象使用枚举,但这可能超出了您当前尝试做的范围。