(1)编程,定义圆类,构建若干个圆对象,输出它们的面积、周长和总个数。
//Circle.java class Circle{ //圆类 private double radius; //半径字段 private double x, y; //圆心坐标字段 private static int num; //圆对象个数字段 public static final double PI = 3.14159; //圆周率常量字段 public Circle(){ //构造方法1 num ++; } public Circle(double radius) throws Exception{ //构造方法2 if (radius < 0) { throw new Exception("负数不能做圆半径"); } else { this.radius = radius; num ++; } } public double getRadius(){ //获取半径方法 return radius; } public void setRadius(double radius) throws Exception{ //设置半径方法 if (radius < 0) { throw new Exception("负数不能做圆半径"); } else { this.radius = radius; } } public static int getNum(){ //获取圆对象个数方法 return num; } public double calcArea(){ //计算面积方法 return PI * radius * radius; } public double calcGirth(){ //计算周长方法 return 2 * PI * radius; } } //Train1.java import java.util.Scanner; public class Train1 { public static void main(String[] args){ System.out.println(" ==== 构建圆对象并计算其面积周长 ===="); try{ Circle aCircle; double radius; String str; Scanner scan = new Scanner(System.in); while(true){ System.out.println("请输入半径(直接按回车键结束程序):"); str = scan.nextLine(); if (str.equals("")) { break; } radius = Double.parseDouble(str); aCircle = new Circle(radius); System.out.printf("构建了半径为%.2f的圆,圆面积%.2f、周长%.2f\n", aCircle.getRadius(), aCircle.calcArea(), aCircle.calcGirth()); System.out.printf("目前圆个数为 %d\n",Circle.getNum()); } scan.close(); } catch(Exception e){ System.out.println("异常:" + e); } finally { System.out.print("——程序结束。"); } } }
(2)编程,定义矩形类,构建若干个矩形对象,输出它们的面积、周长和总个数。
import java.util.Scanner; class Rectangle{ //矩形类 private double length; private double width; private static int num; //矩形对象个数 public Rectangle(){ num ++; } public Rectangle(double length, double width){ this.length = length; this.width = width; num ++; } public double calcArea(){ //计算面积 return length * width; } public double calcGirth(){ //计算周长 return (length + width) * 2; } public double getLength(){ return length; } public void setLength(double length){ this.length = length; } public double getWidth(){ return width; } public void setWidth(double width){ this.width = width; } public int getNum(){ return num; } } public class Train2 { public static void main(String[] args){ System.out.println(" ==== 构建矩形对象并计算其面积周长 ===="); try{ Rectangle aRectangle; double length, width; String str; Scanner scan = new Scanner(System.in); while(true){ System.out.println("请输入长度(直接按回车键结束程序):"); str = scan.nextLine(); if (str.equals("")) { break; } length = Double.parseDouble(str); System.out.println("请输入宽度:"); str = scan.nextLine(); width = Double.parseDouble(str); aRectangle = new Rectangle(length, width); System.out.printf("构建了长%.2f、宽%.2f的矩形,其面积%.2f、周长%.2f\n", aRectangle.getLength(), aRectangle.getWidth(), aRectangle.calcArea(), aRectangle.calcGirth()); System.out.printf("目前矩形个数为 %d\n",aRectangle.getNum()); } scan.close(); } catch(Exception e){ System.out.println("异常:" + e); } finally { System.out.print("——程序结束。"); } } }
侵权联系删除