我必须编写一个封装课程的类。假设一门课程具有三个属性:代号、描述和学分。我必须包括一个构造函数、访问器和修改器,以及方法toString
和equals
.
作为这项作业的一部分,我必须编写一个客户端类来测试该类中的所有方法Course
。我相信我已经完成了课程课程,但在编写客户端时遇到了麻烦。对于我尝试的所有操作,我都会收到错误“无法从静态上下文引用的非静态变量”。我究竟做错了什么?
好的,我已经重写了我的代码。我仍然不确定如何让 mutator 方法工作,也不确定如何要求用户输入以设置新课程的所有值,然后在使用 accessor 和 mutator 方法时将它们输出到屏幕。请帮帮我。谢谢
public class ManualClass
{
public static void main(String[] args)
{
Course compSci = new Test2().new Course("Comp Sci","IT1101",3.0);
System.out.println(compSci+ "\n");
Course dave = new Test2().new Course("Hist1111","World History",4.0);
System.out.print(dave.getCourseCode() + " " + dave.getDescription()
+ " " + dave.getCreditHours() + "\n");
}
public class Course
{
//Instance Variables
private String courseCode;
private String description;
private Double creditHours;
public Course()
{
courseCode = null;
creditHours = 0.0;
description = null;
}
//Constructor
public Course(String courseCode, String description, double creditHours)
{
this.courseCode = courseCode;
this.description = description;
this.creditHours = creditHours;
}
//Accessors (Getters)
public String getCourseCode()
{
return courseCode;
}
public String getDescription()
{
return description;
}
public double getCreditHours()
{
return creditHours;
}
//Mutators (Setters)
public void setCourseCode(String CourseCode)
{
this.courseCode = courseCode;
}
public void setDescription(String description)
{
this.description = description;
}
public void setCreditHours(double creditHours)
{
this.creditHours = creditHours;
}
// toString Method
public String toString()
{
DecimalFormat creditsFormat = new DecimalFormat ("#0.0");
return "Code: " + courseCode + "; Description: "
+ description + "; creditHours: "
+ creditsFormat.format(creditHours);
}
// Equals Method
public boolean equals(Object o)
{
if (!(o instanceof Course))
return false;
else
{
Course objCourse = (Course) o;
if (courseCode.equals(objCourse.courseCode)
&& description == objCourse.description
&& creditHours == objCourse.creditHours)
return true;
else
return false;
}
}
}
}