I've been trying to implement a sorting algorithm to sort this array of Shape objects by their areas and I'm not having much luck. I keep getting a NullPointerException when I sort the list and it refuses to print. I'm a but confused on how to apply to sorting algorithm to things other than integers. I'm extremely new to java so any help would be appreciated. Thank you very much.
public class ShapeApp2 {
public static void sort(Shape arr[]){
int n = arr.length;
for (int i=0; i< n; i++){
int min_area = i;
for (int j = i+1; j < n-1; j++)
if (arr[j].getArea() < arr[min_area].getArea())
min_area = j;
Shape temp = arr[min_area];
arr[min_area] = arr[i];
arr[i] = temp;
}
}
public static void printArray(Shape arr[])
{
int n = arr.length;
for (int i=0; i<n-1; ++i)
System.out.print(arr[i].getDescription()+" ");
System.out.println();
}
/**
* @param args the command line arguments
* @throws java.lang.Exception
*/
public static void main(String[] args) {
Shape[] test = new Shape[10];
System.out.println("Choose a shape or type stop to break away?");
Scanner sc = new Scanner(System.in);
int n = test.length;
for (int i=0; i<test.length; i++) {
String Shape = sc.nextLine();
switch (Shape) {
case "Rectangle":
System.out.println("You have chosen a Rectangle");
test[i] = new Rectangle();
System.out.println("Enter another one now");
break;
case "Square":
System.out.println("You have chosen a Square");
test[i] = new Square();
System.out.println("Enter another one now");
break;
case "Equilateral Triangle":
System.out.println("You have chosen an Equilateral Triangle");
test[i] = new Equilateral_Triangle();
System.out.println("Enter another one now");
break;
case "Right Triangle":
System.out.println("You have chosen a Right Triangle");
test[i] = new Right_Triangle();
System.out.println("Enter another one now");
break;
case "Isosceles Triangle":
System.out.println("You have chosen an Isosceles Triangle");
test[i] = new Isosceles_Triangle();
System.out.println("Enter another one now");
break;
case "Scalene Triangle":
System.out.println("You have chosen a Scalene Triangle");
test[i] = new Scalene_Triangle();
System.out.println("Enter another one now");
break;
case "Stop":
System.out.println("Gotcha, here's your list, Goodbye!");
sort(test);
printArray(test);
break;
case "Print":
sort(test);
printArray(test);
break;
}
if (test[i]==null){
return;
}
}
}
}