72.4k views
19 votes
Import java.util.ArrayList;

import java.util.List;
/**
* Fix the problem in the following code by changing the Point class only,
* without touching the code in main(). Make only the necessary changes.
*/
public class PointTest {
static final class Point {
private double x, y;
List points = new ArrayList<>();
Point(double x, double y) {
this.x = x;
this.y = y;
}
}
public static void main(final String[] args) {
List pointList = new ArrayList<>();
pointList.add(new Point(1, 2));
pointList.add(new Point(3, 4));
System.out.println(pointList.size());
// remove the second Point
pointList.remove(new Point(3, 4));
System.out.println(pointList.size());
// Not removed!
}
}

User Atabex
by
4.6k points

1 Answer

9 votes

Answer:

Step-by-step explanation:

The following code was fixed but it is impossible to fix the entirety of the code without adjusting the Main method as well. This is because the information is being saved in an ArrayList that is saved within the main method. This means that either we need to move the Arraylist outside of the main method or adjust something inside the main method as well to make the code run. In this iteration, I have added an IF statement to the Point method so that it deletes a point if it is being added for a second time. In order to accomplish this, I had to add an extra argument when calling the Point Method in the Main method which would be the ArrayList in which the information is saved.

import java.util.ArrayList;

import java.util.List;

class PointTest {

static final class Point {

private double x, y;

Point(double x, double y, List<Point> points) {

this.x = x;

this.y = y;

for (int i = 0; i < points.size(); i = i+1) {

if ((points.get(i).x == x) && (points.get(i).y == y)) {

points.remove(i);

}

}

}

}

public static void main(final String[] args) {

List<Point> pointList = new ArrayList<>();

pointList.add(new Point(1, 2, pointList));

pointList.add(new Point(3, 4, pointList));

System.out.println(pointList.size());

// remove the second Point

pointList.remove(new Point(3, 4, pointList));

System.out.println(pointList.size());

// REMOVED!!!!!

}

}

User Dan Gravell
by
4.0k points