Miguel Sousa Miguel Sousa - 4 years ago 85
Java Question

No output but boolean is right

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?

Main Class



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);
}
}


Tokenizer



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;
}
}


I really appreciate the help!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download