java - 构造函数和不同的数据类型令人困惑

标签 java string types constructor

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

相关文章:

c++ - 从 CStringW 转换为 std::string 的更简洁的方法?

types - COQ 中 prod 和 sig 类型的关系

javascript - typescript 泛型 : Use output argument type to build input argument type

java - 如何将带有 HTMLDocument 的 JTextPane 中的位置转换为 JTextPane 字符串文本中的位置

java - 确定 Spring Bean 可用的属性?

java - openjdk 仅在从终端启动时显示正确的应用程序图标

java - 如何在 java 中删除字符串缓冲区的最后一个字符?

c# - C#字符串的GetHashCode()是如何实现的?

variables - perl6/rakudo : How can I change the data-type of a variable?

java - 为什么我的 JScrollpane 没有更新删除更改,尽管有 validate() 和 repaint()