I have an abstract class and and few subclasses, and a main class I am have array of shapes and trying to sort the array in descending order of area using comparable
I have a code so far for comparable but it would not sort and would not print .
SHAPE ABSTRACT CLASS
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());
}
}
// DRIVER MAIN CLASS
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);
}
}
}
Considering that your Circle, Rectangle and Triangle classes are correctly implemented, add the line Arrays.sort(shaper);
to sort the array. It will use your Shape's compareTo
method to sort the shapes by area. As is, I do not see any attempt at sorting.
The for-loop where you call CalcArea() method also seems to do nothing, since you never use the return values.