Exercise : Point class errors 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Point {
    int x;                                       // Each Point object has
    int y;                                       // an int x and y inside.

    public void Point(int initX, int initY) {    // Constructor
        initX = x;
        initY = y;
    }

    public static double distanceFromOrigin() {  // Returns this point's
        int x;                                   // distance from (0, 0).
        int y;
        double dist = Math.sqrt(x*x + y*y);
        return dist;
    }

    public void translate(int dx, int dy) {      // Shifts this point's x/y
        int x = x + dx;                          // by the given amounts.
        int y = y + dy;
    }
}

The above Point class has 8 errors. Can you find them all?

Exercise - answer

  1. line 5: constructor header should not have the word void
  2. line 6-7: the assignment statements are backwards; reverse left/right sides of each
  3. line 10: method header should not have the word static
  4. line 11-12: should not re-declare fields x and y
  5. lines 18-19: should not re-declare fields x and y (remove word int)

Exercise - solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class Point {
    int x;
    int y;

    public Point(int initX, int initY) {
        x = initX;
        y = initY;
    }

    public double distanceFromOrigin() {
        double dist = Math.sqrt(x*x + y*y);
        return dist;
    }

    public void translate(int dx, int dy) {
        x = x + dx;
        y = y + dy;
    }
}