package Chapter5; import java.util.Scanner; abstract class Shape1{ public abstract void Sum(); public abstract void Area(); } class Rectang extends Shape1{ double width; double length; public Rectang(){ } public Rectang(double width,double length){ this.width=width; this.length=length; } public void Sum(){ double sum=2*(width+length); System.out.println("长方形周长为:"+sum); } public void Area(){ double sum=width*length; System.out.println("长方形面积为:"+sum); } } class Circle extends Shape1{ double radius; public Circle(){ } public Circle(double radius){ this.radius=radius; } public void Sum(){ double sum=Math.PI*2*radius; System.out.println("圆的周长为:"+sum); } public void Area(){ double sum=Math.PI*radius*radius; System.out.println("圆的面积为:"+sum); } } public class Shape_1 { public static void main(String[] args) { // TODO Auto-generated method stub boolean dd=true; Scanner in=new Scanner(System.in); while(dd){ System.out.println("请选择你要计算的图形:1--长方形,2--圆:"); int s=in.nextInt(); if(s==1){ System.out.println("请输入长方形的宽:"); int aa=in.nextInt(); System.out.println("请输入长方形的长:"); int ss=in.nextInt(); Shape1 sh; sh=new Rectang(aa,ss); sh.Sum(); sh.Area(); dd=false; } else if(s==2){ System.out.println("请输入圆的半径:"); int aa=in.nextInt(); Shape1 sh; sh=new Circle(aa); sh.Sum(); sh.Area(); dd=false; }else{ System.out.println("你输入的有误请重新输入"); dd=true; } } } }
差不多很简洁了
public class Circle extends Shape { private double radius; public Circle(double r){ this.radius = r; } public double Area() { // TODO Auto-generated method stub return Math.PI*radius*radius; } public double Perimeter() { // TODO Auto-generated method stub return Math.PI*2*radius; } } public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); int a = input.nextInt(); if(a==1||a==2){ System.out.println("1***长方形;2***圆形"); if(a==1){ System.out.println("请输入长方形的长:"); int c = input.nextInt(); System.out.println("请输入长方形的宽:"); int w = input.nextInt(); Rectangle rectangle = new Rectangle(c,w); System.out.println("长方形1形面积:"+rectangle.Area()+"矩形周长:"+rectangle.Perimeter()); }else if(a==2){ System.out.println("请输入圆形的半径:"); int r = input.nextInt(); Shape circle = new Circle(r); System.out.println("圆形面积:"+circle.Area()+"圆形周长:"+circle.Perimeter()); } }else{ System.out.println("您的输入有误"); } } }
可以直接用return来写 ,比如return(pi*r*r);pi可以在抽象类中定义成final,之后就不用了多次写了,测试中直接创建子类对象调用方法或者创建父类变量调用,调用可以写在输出语句中比如syso{ " "+变量名.方法名/对象.方法}