赞
踩
题目:
定义容器Container接口。模拟实现一个容器类层次结构,并进行接口的实现、抽象方法重写和多态机制测试。各容器类实现求面积、周长的方法。
第一行n表示对象个数,对象类型用Rectangle、Circle区分,Rectangle表示长方形对象,后面输入长,宽,输入Circle表示圆对象,后面是输入半径。
分别输出所有容器对象的面积之和、周长之和,结果保留小数点后2位。
在这里给出一组输入。例如:
4
Circle
15.7
Rectangle
23.5 100
Circle
46.8
Rectangle
17.5 200
在这里给出相应的输出。例如:
周长之和:56771.13
面积之和:472290.12
- package com.experiment.twoT2;
-
- public class Circle implements Container{
- private double radius;
- public Circle(){
- this.radius=0;
- }
- public Circle(double radius){
- this.radius=radius;
- }
- public double area(){
- return Math.pow(this.radius,2)*pi;
- }
- public double perimeter(){
- return 2*pi*this.radius;
- }
- }

- package com.experiment.twoT2;
-
- public interface Container {
- //接口中的"变量"默认都是 "public static final"类型,即为常量
- double pi=3.14; //在接口里面定义常量不用final修饰,接口里面定义的常量本来就时不可变的
- double area(); //接口里面定义的抽象函数也不用abstract修饰,本来就是抽象的
- double perimeter();
- static double sumofArea(Container c[]) {
- double sumofArea=0.0;
- for(int i=0;i<c.length;i++) {
- sumofArea+=c[i].area();
- }
- return sumofArea;
- }
- static double sumofPerimeter(Container c[]) {
- double sumofPerimeter=0.0;
- for(int i=0;i<c.length;i++) {
- sumofPerimeter+=c[i].perimeter();
- }
- return sumofPerimeter;
- }
- }

- package com.experiment.twoT2;
-
- public class Rectangle implements Container{
- private double length;
- private double width;
- public Rectangle(){
- this.length=0;
- this.width=0;
- }
- public Rectangle(double length,double width){
- this.length=length;
- this.width=width;
- }
- public double area(){
- return this.length*this.width;
- }
- public double perimeter(){
- return (this.length+this.width)*2;
- }
- }

- package com.experiment.twoT2;
-
- import java.util.Scanner;
-
- public class test {
- public static void main(String[] args) {
- int i=0;
- Scanner sc=new Scanner(System.in);
- int n=sc.nextInt();
- Container a[]=new Container[n];
- for(i=0;i<a.length;i++){
- String name=sc.next();
- if(name.equals("Circle")) {
- //double radius=sc.nextDouble();
- a[i]=new Circle(sc.nextDouble()); //在接口数组中传入类与参数
- }
- else if(name.equals("Rectangle")) {
- /*double length = sc.nextDouble();
- double width = sc.nextDouble();*/
- a[i]=new Rectangle(sc.nextDouble(), sc.nextDouble());
- }
- else{
- System.out.println("输入错误,请重新运行该程序!");
- break;
- }
- }
- System.out.printf("周长之和:%.2f%n", Container.sumofPerimeter(a));
- System.out.printf("面积之和:%.2f%n", Container.sumofArea(a));
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。