-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextScanner.java
101 lines (85 loc) · 2.01 KB
/
TextScanner.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.io.*;
import java.util.Iterator;
/* lstting
* cis 120 f18
* hw 09
*/
public class TextScanner implements Iterator<String> {
private BufferedReader b;
private int x;
private String text;
private boolean letter;
public TextScanner(Reader r) {
if (r == null) {
throw new IllegalArgumentException();
}
try {
b = new BufferedReader(r);
text = "";
x = b.read(); // read next char
letter = isLetter(x); // set bool to match with current char
if (x != -1) { // if there is another letter to be read
text += (char) x; // start saving new piece of info
}
} catch (IOException io) {
io.printStackTrace();
}
}
public boolean getState() {
return letter;
}
public static boolean isLetter(int c) { // check if current char is alphabet char
if (c >= 97 && c <= 122) {
return true;
}
return false;
}
public static boolean isName(String s) { // check if current word is name or score
for (int i = 0; i < s.length(); i++) {
if (!isLetter(s.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isValid(int c) {
if (isLetter(c) || (c >= 48 && c <= 57)) {
return true;
}
return false;
}
public void close() {
try {
b.close();
} catch (IOException io) {
io.printStackTrace();
}
}
@Override
public boolean hasNext() {
try {
x = b.read();
while (x != -1 && isValid(x) && letter == isLetter(x)) { // valid char that matches current state
text += (char) x; // add to current piece of info
x = b.read(); // read next char
}
letter = !letter; // else, flip state (from letter to int, or from int to letter)
if (!text.equals("")) {
return true; // if the saved piece of test is nonempty, then there exists info to be read
}
} catch (IOException io) {
io.printStackTrace();
}
return false;
}
@Override
public String next() {
String temp = text;
if (x != -1) {
text = "" + (char) x; // reset text for next piece of info
} else {
text = "";
}
return temp;
}
}