Java:创建一个程序来查找圆柱体的表面积和体积
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30154585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Creating a program to find surface area and volume of a cylinder
提问by Axel
I am trying to make a program with two methods which calculate and return the surface area and volume of a cylinder.
我正在尝试使用两种方法制作一个程序,这些方法计算并返回圆柱体的表面积和体积。
When i run the program the system outputs 0.00 for both and i'm unsure of what i'm doing wrong.
当我运行程序时,系统为两者输出 0.00,我不确定我做错了什么。
Here is my code:
这是我的代码:
public class Circle {
public static int height;
public static int radius;
public static double pi = 3.14;
public Circle(int height, int radius) {
height = 10;
radius = 5;
}
public static double getSurfaceArea() {
int radiusSquared = radius * radius;
double surfaceArea = 2 * pi * radius * height + 2 * pi * radiusSquared;
return surfaceArea;
}
public static double getVolume() {
int radiusSquared = radius * radius;
double volume = pi * radiusSquared * height;
return volume;
}
public static void main(String[] args) {
System.out.println("The volume of the soda can is: " + getVolume() + ".");
System.out.println("The surface area of the soda is: " + getSurfaceArea() + ".");
}
}
}
Thanks in advance.
提前致谢。
回答by samouray
You have to add this line of code to your main:
您必须将这行代码添加到您的主要内容中:
Circle c = new Circle(10,5);
so it would be like so:
所以它会是这样:
public static void main(String[] args) {
Circle c = new Circle(10,5);
System.out.println("The volume of the soda can is: " + c.getVolume() + ".");
System.out.println("The surface area of the soda is: " + c.getSurfaceArea() + ".");
}
and change your circle constructor method to this:
并将您的圆形构造函数方法更改为:
public Circle(int height, int radius) {
this.height = height;
this.radius = radius;
}
回答by Dan12-16
I believe this is what you are looking for:
我相信这就是你要找的:
public class Circle {
public static int height;
public static int radius;
public static double pi = 3.14;
public Circle(int height, int radius) {
this.height = height;
this.radius = radius;
}
public static double getSurfaceArea() {
int radiusSquared = radius * radius;
double surfaceArea = 2 * pi * radius * height + 2 * pi * radiusSquared;
return surfaceArea;
}
public static double getVolume() {
int radiusSquared = radius * radius;
double volume = pi * radiusSquared * height;
return volume;
}
public static void main(String[] args) {
Circle circle = new Circle(10,5);
System.out.println("The volume of the soda can is: " + circle.getVolume() + ".");
System.out.println("The surface area of the soda is: " + cirlce.getSurfaceArea() + ".");
}
}