Below are the code fragments referenced by the reading quiz.
Walker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| // This class represents a walker with two feet.
import java.awt.Image;
import java.awt.Graphics;
public class Walker
{
public static final int PIXELS_PER_INCH = 6;
private Foot leftFoot, rightFoot;
private int stepLength;
private int stepsCount;
// Constructor
public Walker (int x, int y, Image leftPic, Image rightPic)
{ . . . }
// Returns the left foot
public Foot getLeftFoot ()
{ . . . }
// Returns the right foot
public Foot getRightFoot ()
{ . . . }
// Makes first step, starting with the left foot
public void firstStep ()
{ . . . }
// Makes next step
public void nextStep ()
{ . . . }
// Stops this walker (brings its feet together)
public void stop ()
{ . . . }
// Returns the distance walked
public int distanceTraveled ()
{ . . . }
// Draws this walker
public void draw (Graphics g)
{ . . . }
} |
Pacer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| // A subclass of Walker that adds the turnAround method.
import java.awt.Image;
public class Pacer extends Walker
{
// Constructor
public Pacer (int x, int y, Image leftPic, Image rightPic)
{ . . . }
// Turns this Pacer 180 degrees
// Precondition: the left and right feet are side by side
public void turnAround ()
{ . . . }
public void turnRight ()
{ . . . }
public void turnLeft ()
{ . . . }
} |
PacerTest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| . . . imports omitted to save space . . .
public class PacerTest extends JPanel
{
// Called automatically when the panel needs repainting
public void paintComponent (Graphics g)
{
super.paintComponent (g);
int x = 100;
int y = 300;
Pacer p = new Pacer (x, y, lshoe, rshoe);
p.draw (g);
p.firstStep ();
p.nextStep ();
p.stop ();
p.turnLeft ();
p.draw (g);
p.firstStep ();
p.nextStep ();
p.stop ();
p.turnRight ();
p.draw (g);
// Draw a cursor at the expected center of the first "shoe":
g.drawLine (x - 50, y, x + 50, y);
g.drawLine (x, y - 50, x, y + 50);
}
. . . other methods omitted to save space . . .
} |