我目前正在学习 Java 类(class)(是我的学士类(class)的最后一门类(class),是的),我在尝试理解类(class)并解决下面这个问题时遇到了很大的困难。我目前使用的教科书非常令人困惑,我尝试使用其他在线资源来找出我做错了什么,但我似乎仍然卡在下面的问题上。每当我尝试运行该程序时,我得到的答案都是 0.00.0
,这是由于我自己错误地为 cyclone1
分配了值吗?另外,对于 toString() 类,我该怎么做呢?无论我能做什么,我在将 double
转换为 String
时总是遇到错误。
如有任何帮助,我们将不胜感激。
谢谢。
提示
Implement the class called
Cylinder
shown in UML below. The constructor accepts and initializes the radius and height for theCylinder
, while accessors and mutators allow them to be changed after object construction. The class also include methods that calculate and return the volume and surface area of theCylinder
. Lastly, it contains atoString
method that returns the name of the shape, its radius, and its height. Create amain
method which instantiates 4Cylinder
objects (any parameters), display them withtoString()
, change one parameter (your choice) in each, and display them again. [15 points]
UML
代码
import java.util.*;
import java.text.*;
import java.io.*;
import java.lang.*;
class Cylinder
{
private double radius, height, area, volume;
public Cylinder(double height, double radius) {
radius = 0.0;
height = 0.0;
}
public double getRadius() {
return radius;
}
public double getHeight() {
return height;
}
public double getArea() {
double area = (2 * Math.PI * radius * height) + (2 * Math.PI * Math.pow(radius, 2));
return area;
}
public void setRadius(double r) {
radius = r;
}
public void setHeight(double h) {
height = h;
}
public double calcVolume() {
double volume = Math.PI * Math.pow(radius, 2) * height;
return volume;
}
public String toString (){
StringBuilder StBuild = new StringBuilder();
StBuild.append(radius).append(height);
return StBuild.toString();
}
public static void main(String[] args) {
Cylinder cylinder1 = new Cylinder(5, 5);
System.out.println(cylinder1);
}
}
最佳答案
由于这显然是家庭作业,我不会给你答案,但我会尝试解释一些事情。
这个:
public Cylinder(double height, double radius) {
radius = 0.0;
height = 0.0;
}
是一个构造函数。当您创建一个对象(和类的实例)时,您可以调用它。您可以通过以下方式调用它:
Cylinder cylinder1 = new Cylinder(5, 5);
但是你的类(class)里发生了什么?当你调用构造函数时,你真的保存了你想要的值吗?
至于 toString 方法,您可以为 double (height.toString) 调用 toString,也可以执行我总是最终执行的操作,即通过向其添加字符串来作弊。
public String toString (){
return "Cylinder [ h: " + height + " - r: " + radius + " - v: " + calcValume() + "]";
}
关于java - 创建圆柱体类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514691/