I am studying for my software Engineering test and i am doing code to do the tests later. the tests are already doing what I want but I need the output too.
Can you help me understand why the output isn't working?
import java.io.*;
public class JavaStreamTokenizerExample {
public static void main(String[] args) throws IOException {
Reader reader = new StringReader("rvew rwe");
Tokenizer toke = new Tokenizer(reader);
boolean result = toke.doTokenizer(toke);
System.out.println(result);
}
}
import java.io.*;
public class Tokenizer {
private final Reader reader;
public Tokenizer(Reader reader) {
this.reader = reader;
}
public boolean doTokenizer(Tokenizer readers) throws IOException {
int intValueOfChar;
String targetString = "";
while ((intValueOfChar = readers.reader.read()) != -1) {
targetString += (char) intValueOfChar;
}
if (targetString.length() >= 150) {
return false;
}
if (targetString.equals("") || targetString.equals(" ")) {
return false;
} else {
StreamTokenizer tokenizer = new StreamTokenizer(readers.reader);
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
System.out.println(tokenizer.sval);
}
return true;
}
}
public Reader getReader() {
return reader;
}
}
Take a closer look at what this loop is doing:
while ((intValueOfChar = readers.reader.read()) != -1) {
targetString += (char) intValueOfChar;
}
It's actually reading each character and concatenating it to targetString
; i.e., you've read everything. When the second loops is called
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
System.out.println(tokenizer.sval);
}
there is nothing left to read, so it immediately evaluates to false and execution moves to the return true
statement.
You need to reset the reader.