-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScanner.java
65 lines (57 loc) · 1.97 KB
/
Scanner.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
package Lab3;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Scanner{
// the symbols that the scanner should stop at
// "{}" are used for the comments and "\n\r" are used for newlines
private String[] symbols = {"+", "-", "*", "/", "=", "<", "(", ")", ";", ":", "{", "}", "\n", "\r"};
private StringTokenizer tokenizer;
// to keep track of the lines
private int line = 1;
// to check whether it is in the middle of a comment
private boolean comment = false;
public Scanner(String input) {
tokenizer = new StringTokenizer(input, Arrays.toString(symbols), true);
}
//the method to retrieve the next token in the scanner
public String nextToken(){
String token = "";
if (tokenizer.hasMoreTokens()) {
while (token.isBlank()) { // ignore all whitespace
if (token.contentEquals("\n"))
line++;
if (tokenizer.hasMoreTokens())
token = tokenizer.nextToken();
else {
token = "";
break;
}
}
if (token.contentEquals("{")) {
comment = true;
while (!token.contentEquals("}")) {// skip everything until closing bracket
if (token.contentEquals("\n"))
line++;
if (tokenizer.hasMoreTokens())
token = tokenizer.nextToken();
else {
token = "";
return token;
}
}
comment = false;
return nextToken(); //recursively get next token after the comment
}
if (!token.isBlank()) {
return token;
}
}
return token;
}
public int getLine() {
return line;
}
public boolean isComment() {
return comment;
}
}