I am slowly but surely learning java and I would really appreciate it if I could
ID: 3581450 • Letter: I
Question
I am slowly but surely learning java and I would really appreciate it if I could recieve help with this inner class problem:
Repeat Exercise E10.5, making the Measurer into an inner class inside the main method.
(Excersice 10.5: Using a different Measurer object, process a set of Rectangle objects to find the rectangle
with the largest perimeter.)
Class information:
public class Data
{
/**
Computes the average of the measures of the given objects.
@param objects an array of Measurable objects
@return the average of the measures
*/
public static double average(Measurable[] objects)
{
double sum = 0;
for (Measurable obj : objects)
{
sum = sum + obj.getMeasure();
}
if (objects.length > 0) { return sum / objects.length; }
else { return 0; }
}
public static Measurable max(Measurable[] measurables){
Measurable largest = measurables[0];
for (int i=1; i < measurables.length; i++){
if (measurables[i].getMeasure() > largest.getMeasure()){
largest = measurables[i];
}
}
return largest;
}
}
Explanation / Answer
import java.awt.Rectangle;
/**
Test data with measurable , Measure objects
*/
public class Data
{
public static void main(String[] args)
{
class RectangleMeasurer implements Measurer
{
public double measure(Object anObject)
{
Rectangle aRectangle1 = (Rectangle) anObject;
double perimeter = 2*(aRectangle1.getWidth()+aRectangle1.getHeight());
return perimeter;
}
}
Measurer m = new RectangleMeasurer();
DataSet d1 = new DataSet(m);
d1.add(new Rectangle(5, 10, 20, 30));
d1.add(new Rectangle(10, 20, 30, 40));
d1.add(new Rectangle(20, 30, 5, 10));
System.out.println("Average perimeter: " + d1.getAverage());
System.out.println("Expected: 616.6666667");
Object max = d1.getMaximum();
System.out.println("Largest perimeter: " + m.measure(max));
System.out.println("Expected: 1200");
// default measure testing
d1 = new DataSet();
d1.add(new BankAccount(2000));
d1.add(new BankAccount(200));
d1.add(new BankAccount(20000));
System.out.println("Average balance: " + d1.getAverage());
System.out.println("Expected: 7400");
Measurable max2 = (Measurable) d1.getMaximum();
System.out.println("Highest balance: " + max2.getMeasure());
System.out.println("Expected: 20000");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.