我有一个抽象类,很少有子类,还有一个主类我有形状数组,并尝试使用可比的>>按面积的降序对数组进行排序
到目前为止,我有一个可比较的代码,但它无法排序和打印。
形状抽象类
import java.text.*; public abstract class shape implements Comparable<shape> { private int id; private String label; private static int counter = 1; // to keep count and unique over all classes private static DecimalFormat df2 = new DecimalFormat("#.##"); public shape(String label) { this.id = counter; counter ++ ; //this is counter for unique id can also have a default constructor seperate for count this.label = label; } public int getId() { return id; } public String getLabel() { return label; } public interface Comparable { public int compareTo(shape o); } public int compareTo(shape o) { if (this.CalcArea() > o.CalcArea()) return 1; else if (this.CalcArea() < o.CalcArea()) return -1; else return 0; } //to calculate area= abstract method public abstract double CalcArea(); // this is the prototype and has to be used once in derived classes public String toString() { //df2.format(CalcArea()) return "ID " + this.id + ": the shape is " + label + " and the area calculated is "+ df2.format(CalcArea()); } }
//驾驶员主要类别
import java.util.*;
public class DrawingApp {
/*public DrawingApp() {
}*/
public static void main(String[] args) {
int shapeType;
int i; //two for loops so better here
//next gaussian if using double
shape[] shaper = new shape[10]; //instantiating array object not the shape
Random num = new Random();
Random num1 = new Random(); //*100 + 1
for ( i = 0; i < 10 ; i++) {
shapeType = num.nextInt()% 2 ;
if(shapeType == 0 ) {
shaper[i] = new circle((num1.nextDouble()*9)+1); //can use random as the shapes are created randomly and array of ten
}else if(shapeType == 1) {
shaper[i] = new Rectangle((num1.nextDouble()*9)+1,(num1.nextDouble()*9)+1);
}else {
shaper[i] = new Triangle((num1.nextDouble()*9)+1,(num1.nextDouble()*9)+1);
}
}
for ( i = 0; i < 10 ; i ++) {
shaper[i].CalcArea();
}
for(shape s : shaper){
System.out.println(s);
}
}
}
我有一个抽象类和很少的子类,而我有一个主类,它具有形状数组,并尝试使用具有可比性的数组按面积降序对数组进行排序,到目前为止,我有代码...]]
Arrays.sort(shaper);
行以对数组进行排序。它将使用Shape的compareTo
方法按面积对形状进行排序。照原样,我看不到任何排序尝试。 您在其中调用CalcArea()方法的for循环似乎也无济于事,因为您从未使用过返回值。