这题目只能比较两个图形的的面积大小和周长大小,现在我要比较N个图形的大小,但不知道怎么用循环。有那个给小弟解决一下?我是初学者要详细一点
public class toStringDemo {
public static void main(String args[]){
Rectangle r=new Rectangle(10,10);
Rectangle r1=new Rectangle(10,20);
Circle c=new Circle(10);
Circle c1=new Circle(20);
/*
* 多态(继承,重写):
* 不同的对象调用相同的方法
* 在执行过程中,会根据自身所在的类进行动态选择调用。
*/
//面积的比较
maxArea(r,c1);
maxArea(r,r1);
maxArea(c,c1);
//周长的比较
maxCyan(r,r1);
maxCyan(c,c1);
}
public static void maxArea(Shape r,Shape c){
if(r.area()>c.area()){
System.out.println(r);
}
else{
System.out.println(c);
}
}
public static void maxCyan(Shape r,Shape c){
if(r.cyan()>c.cyan()){
System.out.println(r);
}
else {
System.out.println(c);
}
}
}
public abstract class Shape {
public abstract double area();
public abstract double cyan();
}
public class Circle extends Shape{
private double r;
public Circle() {
super();
}
public Circle(int r) {
this.r=r;
}
public String toString(){
return "圆:半径="+this.r+"\t面积="+this.area()+"\t 周长="+this.cyan();
}
public double area(){
return this.r*this.r*Math.PI;
}
public double cyan(){
return 2*r*Math.PI;
}
}
public class Rectangle extends Shape{
private double width,length;
public Rectangle(double width, double length) {
super();
this.width = width;
this.length = length;
}
public boolean equals(Object arg0) {
Rectangle r=(Rectangle)arg0;
if(this.width==r.width&&this.length==r.length){
return true;
}
else{
return false;
}
}
public String toString(){
return "长方形:宽="+this.width+"\t长="+this.length+"\t面积="+this.area()+"\t 周长="+this.cyan();
}
public double area(){
return this.width*this.length;
}
public double cyan(){
return 2*(this.width+this.length);
}
}