我是 Java 的新手,正在完成一项作业。我应该创建自己的类“Cylinder”并从中调用方法以便能够打印出半径和高度,然后更改它并再次打印出来。我得到它来打印 cylinder1 和 cylinder1.setRadius/setHeight 的设置值..我的问题是我必须让它打印像 Cylinder Radius: 和 Height:...但是当它打印时我得到的是 3.04.0或设置为...我花了很长时间试图解决这个问题,请提供任何帮助!
public class Funtimes{
public static void main(String[] args){
Cylinder cylinder1= new Cylinder(1,2);
System.out.println(cylinder1);
cylinder1.setRadius(3);
cylinder1.setHeight(4);
System.out.println(cylinder1);
}}
class Cylinder
{
private double radius, height, area, volume;
public Cylinder(double height, double radius){
this.radius = radius;
this.height=height;
}
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);
}
}
最佳答案
修改你的toString()
public String toString () {
return String.format("Radius: %s Height: %s", radius, height);
}
关于java - 创建自定义类! java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366154/