Exercise : Point class errors

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

    public static void draw(Graphics g) {    // draws this point
        g.fillOval(p1.x, p1.y, 3, 3);
        g.drawString("(" + p1.x + ", " + p1.y + ")", p1.x, p1.y);
    }

    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;
    }

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

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

Exercise - answer

  1. line 6: method header should not have the word static
  2. line 12: should not re-declare field x (delete word int)
  3. line 13: should not re-declare field y (delete word int)
  4. line 17: should not declare Point p
  5. line 18: should not use p. in front of the fields

Exercise - solution

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

    public void draw(Graphics g) {           // draws this point
        g.fillOval(x, y, 3, 3);
        g.drawString("(" + x + ", " + y + ")", x, y);
    }

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

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