【发布时间】:2015-10-03 21:41:49
【问题描述】:
我对 Java 和编码还很陌生,但在 Java 材料的这一点上,我还没有遇到任何问题。我真正无法理解的是类和方法的实际工作方式。在过去的几个小时里,我一直在尝试实现这一点,但无济于事:
实现下面 UML 中显示的名为 Cylinder 的类。构造函数接受并初始化圆柱体的半径和高度,而 accessors 和 mutators 允许在对象构造后更改它们。该类还包括计算和返回圆柱体的体积和表面积的方法。最后,它包含一个返回形状名称、半径和高度的 toString 方法。创建一个实例化 4 个 Cylinder 对象(任何参数)的 main 方法,用toString() 显示它们,更改每个参数(您的选择),然后再次显示它们。
UML:
这是我目前拥有的代码:
class Cylinder {
private double radius;
private double height;
// Method #1
private void rad (){
}
// Constructor
public Cylinder (double radius, double height){
this.radius = radius;
this.height = height;
}
// Method #2 for calculating volume.
double calcVolume (){
double volume = Math.PI * Math.pow(radius, 2) * height;
return volume;
}
// Method #3 for calculating surface area.
double calcArea (){
double area = (2 * Math.PI * radius * height) + (2 * Math.PI * Math.pow(radius, 2));
return area;
}
// toString method.
public String toString (){
StringBuilder sb = new Stringbuilder();
sb.append(radius).append(height);
return sb.toString();
}
}
公开课 Murray_A03Q1 {
public static void main(String[] args) {
Cylinder cylinder1 = new Cylinder(5, "can");
System.out.println(cylinder1);
Cylinder cylinder2 = new Cylinder(6, "cup");
Cylinder cylinder3 = new Cylinder(7, "jar");
Cylinder cylinder4 = new Cylinder(8, "paper roll");
}
}
我真正不明白的是如何使用 'get' 和 'set' 方法。另外,我不完全确定如何实现 toString 方法。
以下我不知道如何纠正的错误是:
构造函数
Cylinder()未定义 - 气缸cylinder1 = new Cylinder();Stringbuilder 无法解析为 - StringBuilder
sb = new Stringbuilder();
感谢您的帮助!
【问题讨论】:
标签: class methods constructor get tostring