Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Here is a program that is supposed to find the largest x value in the ArrayList

ID: 3657695 • Letter: H

Question

Here is a program that is supposed to find the largest x value in the ArrayList of Rectangles. But there are errors: 3 syntax and 2 logic errors. Find the errors, fix them and upload the corrected code. Put a comment on each line you change saying what you changed. Do not change anything that is not an error. import java.awt.Rectangle; public class Errors1 { public static void main(String[] args) { ArrayList rectangles; rectangles.add(new Rectangle(10, 30, 50, 60)); rectangles.add(new Rectangle(25, 15, 40, 70)); rectangles.add(new Rectangle(15, 40, 100, 60)); double max = Integer.MIN_VALUE; for (i = 0; i <= rectangles.size(); i++) { if (max > rectangles.get(i).getX()) { max = rectangles.get(i).getX(); } } System.out.println(max); } }

Explanation / Answer

import java.awt.Rectangle;
// syntax error: import ArrayList
import java.util.ArrayList;

public class Errors1
{
public static void main(String[] args)
{
// logic error: instantiation
// ArrayList rectangles;
ArrayList rectangles = new ArrayList();

rectangles.add(new Rectangle(10, 30, 50, 60));
rectangles.add(new Rectangle(25, 15, 40, 70));
rectangles.add(new Rectangle(15, 40, 100, 60));
double max = Integer.MIN_VALUE;

// syntax error: i undeclared
// for (i = 0; i <= rectangles.size(); i++)
for (int i = 0; i <= rectangles.size(); i++)
{
// syntax error: ArrayList contains type object
// logic error: change max if it's less than not greater than
// if (max > rectangles.get(i).getX())
// {
// max = rectangles.get(i).getX();
// }

if (max < ((Rectangle)rectangles.get(i)).getX() )
{
max = ((Rectangle)rectangles.get(i)).getX();
}
}
System.out.println(max);
}
}