gpt4 book ai didi

java - 创建圆柱类

转载 作者:行者123 更新时间:2023-11-30 06:13:42 26 4
gpt4 key购买 nike

我目前正在上一门 Java 类(class)(是我单例汉的最后一门类(class)),我在尝试理解类(class)和解决下面的这个问题时遇到了非常困难的时间。我目前使用的教科书非常困惑,我尝试使用其他在线资源来弄清楚我做错了什么,但我似乎仍然停留在下面的问题上。每当我尝试运行程序时,我得到的答案都是 0.00.0,这是否是因为我错误地为 cylinder1 赋值?另外,对于 toString() 类,我该怎么做呢?无论我能做什么,我总是在将 double 转换为 String 时遇到错误。

如有任何帮助,我们将不胜感激。

谢谢。

提示

Implement the class called Cylinder shown in UML below. The constructor accepts and initializes the radius and height for the Cylinder, 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 the Cylinder. Lastly, it contains a toString method that returns the name of the shape, its radius, and its height. Create a main method which instantiates 4 Cylinder objects (any parameters), display them with toString(), 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);

但是你的类里面发生了什么?当您调用构造函数时,您真的保存了您想要的值吗?

至于 toString 方法,您可以为 double (height.toString) 调用 toString,或者您可以只做我经常做的事情,即通过向它添加一个字符串来作弊。

public String toString (){
return "Cylinder [ h: " + height + " - r: " + radius + " - v: " + calcValume() + "]";
}

关于java - 创建圆柱类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com