-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathifCommand.java
73 lines (61 loc) · 1.72 KB
/
ifCommand.java
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
69
70
71
72
73
import java.util.ArrayList;
import java.util.Scanner;
public class ifCommand extends Command {
public static final int IF_MODE = 1;
public static final int ELSE_MODE = 2;
private ArrayList<Command> ifList; //save commands inside the if curly braces
private ArrayList<Command> elseList; //save commands inside the else curly braces
private String logicalExpr; //save expression inside the if parenthesis
private int mode; //if or else mode
public ifCommand(){
this.ifList = new ArrayList<Command>();
this.elseList = new ArrayList<Command>();
this.mode = IF_MODE;
}
public void setLogicalExpr(String expr){
this.logicalExpr = expr;
}
public String getLogicalExpr(){
return this.logicalExpr;
}
public void changeMode(int mode){
this.mode = mode;
}
public int getMode(){
return this.mode;
}
public void addCommand(Command c){
if (this.getMode() == IF_MODE)
this.ifList.add(c);
else
this.elseList.add(c);
}
public void run(){
for (Command c: ifList){
c.run();
}
if(!elseList.isEmpty()){
for(Command c: elseList){
c.run();
}
}
}
public String writeJava(){
StringBuilder str = new StringBuilder();
str.append("if (");
str.append(this.getLogicalExpr());
str.append("){\n");
for (Command c: ifList){
str.append(c.writeJava());
}
str.append("}\n");
if (!elseList.isEmpty()){
str.append("else{\n");
for (Command c: elseList){
str.append(c.writeJava());
}
str.append("}\n");
}
return str.toString();
}
}