-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrover.java
More file actions
68 lines (66 loc) · 1.39 KB
/
rover.java
File metadata and controls
68 lines (66 loc) · 1.39 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class rover {
final static int N = 1;
final static int E = 2;
final static int S = 3;
final static int W = 4;
int x = 0;
int y = 0;
int face = N;
public void setPosition(int x, int y, int d) {
this.x = x;
this.y = y;
this.face = d;
}
public void printPosition(rover x) {
System.out.print(x.x + " " + x.y + " ");
if (x.face == 1) {
System.out.println('N');
} else if (x.face == 2) {
System.out.println('E');
} else if (x.face == 3) {
System.out.println('S');
} else if (x.face == 4) {
System.out.println('W');
}
}
public void moveRover(String commands) {
for (int x = 0; x < commands.length(); x++) {
start(commands.charAt(x));
}
}
public void start(char x) {
if (x == 'L'){
turnleft();
} else if (x == 'M') {
moveForward();
} else if (x =='R') {
turnright();
}
}
public void turnleft() {
face = (face - 1) < N ? W : face -1;
}
public void turnright() {
face = (face + 1) > W ? N : face + 1;
}
public void moveForward() {
if (face == N) {
this.y++;
} else if (face == E) {
this.x++;
} else if (face == S) {
this.y--;
} else if (face == W) {
this.x--;
}
}
public static void main(String[] args){
rover Rover = new rover();
Rover.setPosition(1,2,N);
Rover.moveRover("LMLMLMLMM");
Rover.printPosition(Rover);
Rover.setPosition(3,3,E);
Rover.moveRover("MMRMMRMRRM");
Rover.printPosition(Rover);
}
}