Java编程实现圆柱体表面积和体积的计算,要求从键盘上输入圆的半径和高,然后输出结果。
题目分析:首先定义Circle类,然后在main方法中创建Circle类的对象c,利用对象c访问其成员方法setR(),为其成员变量r赋值,访问其成员方法setH(),为其成员变量h赋值。最后通过对象c调用getArea()和getVolume()方法分别计算圆柱体表面积和体积并输出结果。
代码:
1 package com.web; 2 3 import java.util.Scanner; 4 5 class Circle{ 6 public static final double PI=3.14; 7 8 private double r; 9 private double h; 10 11 public Circle() { 12 super(); 13 } 14 15 public Circle(double r, double h) { 16 super(); 17 this.r = r; 18 this.h = h; 19 } 20 21 public double getR() { 22 return r; 23 } 24 25 public void setR(double r) { 26 this.r = r; 27 } 28 29 public double getH() { 30 return h; 31 } 32 33 public void setH(Double h) { 34 this.h = h; 35 } 36 37 public static double getPi() { 38 return PI; 39 } 40 41 public double getArea(){ 42 return PI * r * r * 2 + h * 2 * PI * r; 43 } 44 45 public double getVolume(){ 46 return PI * r * r * h; 47 } 48 49 50 51 } 52 public class CylinderTest { 53 public static void main(String[] args) { 54 Scanner sc = new Scanner(System.in); 55 Circle c = new Circle(); 56 57 System.out.println("请输入圆的半径:"); 58 c.setR(sc.nextDouble()); 59 60 System.out.println("请输入圆柱的高:"); 61 c.setH(sc.nextDouble()); 62 63 System.out.printf("圆柱的面积为:"+ c.getArea()); 64 System.out.printf("圆柱的体积为:"+ c.getVolume()); 65 } 66 67 }