本文博主原创文章,未经博主允许不得转载
定义一个圆柱体类(Circle)要求如下:
(1)成员变量:r(double型)表示半径;h(double型)表示高度。
(2)无参构造函数:输出"This is a Cylinder."。
(3)成员方法:
setR();设置半径;
getR();获得半径;
setH();设置高度;
getH();获得高度;
getArea();计算圆柱表面积;
getVolumn();计算圆柱体积;
(4)根据类Circle的定义,创建一个Circle类的对象,在控制台中提示用户输入圆柱体的的半径(r)和高度(h);
读入用户输入后,显示该圆柱的半径、高、表面积和体积。
方法一:
public class Circle {
private double r;
private double h;
public Circle()
{
System.out.println("This is a Circle.");
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
public void setCircle(double r1,double h1)
{
r=r1;
h=h1;
}//接收CircleTest控制台输入的数据
public double getArea()
{
return this.r*this.r*3.14*2+this.r*3.14*2*this.h;
}
public double getVolumn()
{
return 3.14*this.r*this.r*this.h;
}
}
这两段代码要在一个包里哦!!!
import java.util.*;
public class CircleTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Circle circle=new Circle();//创建Circle类的对象
System.out.println("Please enter two number r and h.");
Scanner sc=new Scanner(System.in);
//控制台输入数据
double r1=sc.nextDouble();
double h1=sc.nextDouble();
circle.setCircle(r1, h1);
sc.close();
String output="圆柱的半径是:"+r1+"\n圆柱的高度是:"+h1+"\n圆柱的面积 是:"+circle.getArea()+"\n圆柱的体积是:"+circle.getVolumn()+"\n";
System.out.print(output);
}
}
方法二:
import java.util.*;
public class Cylinder {
private double r;
private double h;
//不一样之处
public Cylinder()
{
this.r=0;
this.h=0;
}
public Cylinder(double r,double h)
{
this.r=r;
this.h=h;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
public double getArea()
{
double r=this.r;
double h=this.h;
double Area=2*3.14*r*r+2*3.14*r*h;
return Area;
}
public double getVolumn()
{
double Volumn=3.14*this.r*this.r*this.h;
return Volumn;
}
public void show()
{
System.out.println("This is a Cylinder.");
System.out.println("Please enter r and h:");
Scanner sc=new Scanner(System.in);
this.setR(sc.nextDouble());
this.setH(sc.nextDouble());
System.out.println("圆柱的半径:"+this.r);
System.out.println("圆柱的高度:"+this.h);
System.out.println("圆柱的面积:"+this.getArea());
System.out.println("圆柱的体积:"+this.getVolumn());
sc.close();
}
}
这两段代码要放在一个包里哦!!!
public class CylinderTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cylinder cylinder=new Cylinder();
cylinder.show();
}
}