Question: Write a java program that has 4 classes, Rectangle, AreaComparator, PerimeterComparator, Main/Driver class. The Rectangle class should contain the height/width of the rectangle and all
Write a java program that has 4 classes, Rectangle, AreaComparator, PerimeterComparator, Main/Driver class. The Rectangle class should contain the height/width of the rectangle and all standard class methods (getters/setters/constructor/tostring/etc). Also include getArea and getPerimeter methods. The comparator classes should contain correctly written comparators for Rectangle objects (page 25 has an example for comparing Strings). In the Main/Driver class, include the findMax method provided (do not edit this method) and create an array of at least 5 rectangles. Use the findMax and each comparator class object to determine which rectangle is the largest and print it out. Examples to test with: H:1, W:100(large perimeter) H:25, W:20(large area)
1 // Generic findMax, with a function object.
2 // Precondition: a.size( ) > 0.
3 public static
4 AnyType findMax( AnyType [ ] arr, Comparator cmp )
5 {
6 int maxIndex = 0;
7
8 for( int i = 1; i < arr.size( ); i++ )
9 if( cmp.compare( arr[ i ], arr[ maxIndex ])>0)
10 maxIndex = i; 11 12 return arr[ maxIndex ];
13 }
14
15 class CaseInsensitiveCompare implements Comparator
16 {
17 public int compare( String lhs, String rhs )
18 { return lhs.compareToIgnoreCase( rhs ); }
19 }
20
21 class TestProgram
22 {
23 public static void main( String [ ] args )
24 {
25 String [ ] arr = { "ZEBRA", "alligator", "crocodile" };
26 System.out.println( findMax( arr, new CaseInsensitiveCompare( ) ) )
27 }
28 } --------------------------------------------------------comparator ex---------------------------------------------------------------
import java.util.Comparator;
public class ComparatorExamples {
/*BEGIN:DO NOT MODIFY*/
public static
{
int maxIndex = 0;
for(int i = 1; i < arr.length; i++)
{
if(cmp.compare(arr[i], arr[maxIndex]) > 0)
{
maxIndex = i;
}
}
return arr[maxIndex];
}
/*END:DO NOT MODIFY*/
public static void main(String[] args)
{
String[] arr = new String[]{"ABC", "CDE", "EFG", "zde", "ZFG"};
System.out.println(findMax(arr, new CaseInsensitiveCompare()));
}
/*Comparator Example*/
private static class CaseInsensitiveCompare implements Comparator
{
//lhs = left hand side, rhs = right hand side
public int compare(String lhs, String rhs)
{
return lhs.compareToIgnoreCase(rhs);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
