Main类
package main;
import shape.Rectangle;
import shape.Utility;
public class Main {
public static void main(String[] args) {
Rectangle[] rectangles = new Rectangle[10];
for(int count = 0; count < rectangles.length; count++) rectangles[count] = new Rectangle(Math.random()*100,Math.random()*100);
Utility.output(rectangles);
System.out.println();
System.out.println("The rectangle with the largest area:");
System.out.printf("[%.2f, %.2f] – %.2f\n\n", Utility.getMaxRectangle(rectangles).getWidth(),
Utility.getMaxRectangle(rectangles).getHeight(),
Utility.getMaxRectangle(rectangles).getArea());
Utility.sort(rectangles);
Rectangle.setColor("RED");
Utility.output(rectangles);
}
}
Rectangle类
package shape;
public class Rectangle {
private double width;
private double height;
private static String color = "BLACK";
public Rectangle(){}
public Rectangle(double width, double height){
this.width = width;
this.height = height;
}
public double getArea(){
return width*height;
}
public double getPermeter(){
return 2*(width+height);
}
public double getWidth(){
return width;
}
public void setWidth(double width){
this.width = width;
}
public double getHeight(){
return height;
}
public void setHeight(double height){
this.height = height;
}
public static String getColor(){
return color;
}
public static void setColor(String color){
Rectangle.color = color;
}
}
Utility类
package shape;
public class Utility {
public static int compare(Rectangle rect1, Rectangle rect2){
if(rect1.getArea() == rect2.getArea()) return 0;
else return rect1.getArea()>rect2.getArea()?1:-1;
}
public static void sort(Rectangle[] rectangles){
for (int i = 0; i < rectangles.length - 1; i++) {
for (int j = 0; j < rectangles.length - 1 - i; j++) {
if (rectangles[j].getArea() < rectangles[j + 1].getArea()) {
Rectangle temp = rectangles[j + 1];
rectangles[j + 1] = rectangles[j];
rectangles[j] = temp;
}
}
}
}
public static Rectangle getMaxRectangle(Rectangle[] rectangles){
int max = 0;
for(int i = 1; i < rectangles.length; i++){
if(rectangles[max].getArea() < rectangles[i].getArea()) max = i;
}
return rectangles[max];
}
public static void output(Rectangle[] rectangles){
System.out.println("共有"+rectangles.length+"个矩形对象,颜色是:"+ Rectangle.getColor());
for (Rectangle rectangle : rectangles) {
System.out.printf("[%.2f, %.2f] – %.2f\n", rectangle.getWidth(), rectangle.getHeight(), rectangle.getArea());
}
}
}