2

我正在通过构造函数传递一个字符串并将其值分配给 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
}
4

2 回答 2

1

您不能将 A 类型的对象分配给 B 类型的引用变量(除非 A 是 B 的子类)。您不能将 a 分配String给 a Grade

您将需要创建一个Grade使用String

gradeReceived = new Grade(grade);

new运算符调用构造函数并public Grade(String grade)返回一个新Grade对象。

于 2013-09-17T19:03:02.907 回答
0

您将需要某种转换器或映射来将字符串值(例如“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);
    ...
}

如果没有任何转换要做。

您也可以为 Grade 对象使用枚举,但这可能超出了您当前尝试执行的范围。

于 2013-09-17T19:08:30.557 回答