1

Considering the below code for an exercise problem, where is the specification that says roughly: "Upon the call to readTokens(), wait for the user to press carriage return and then continue execution."

I'm not fully understanding why my code works, why does the program pause after "Enter Data: " is displayed and wait for a carriage return? Where is this behavior defined and how can it be changed?

import java.io.*;
import java.util.LinkedList;

public class StreamTokeTwo {

private int ttype = 0;
StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(
        new InputStreamReader(System.in)));

private void setupTokenizer() {
    tokenizer.resetSyntax();
    tokenizer.wordChars(33, 126);
    tokenizer.whitespaceChars(0, 32);
    tokenizer.whitespaceChars(44,44);
    tokenizer.whitespaceChars(47,47);
    tokenizer.eolIsSignificant(true);
}

private String[] readTokens() {
    LinkedList<String> list = new LinkedList<String>();
    String[] array = null;

    do {
        try {
            ttype = tokenizer.nextToken();
        } catch (Exception e) {
            System.exit(1);
        }
        if (ttype == StreamTokenizer.TT_WORD) {
            list.add(tokenizer.sval);
        }
    } while (ttype != StreamTokenizer.TT_EOL);

    array = list.toArray(new String[0]);
    return array;
}

public static void main(String[] args) {
    StreamTokeTwo streamToke = new StreamTokeTwo();
    streamToke.setupTokenizer();

    for (int i = 0; i < 5; ++i) {
        System.out.print("Enter data: ");
        String[] array = streamToke.readTokens();
        for (String str : array) {
            System.out.print(str + " ");
        }
        System.out.println();
    }
}
}
Steve M
  • 9,296
  • 11
  • 49
  • 98

2 Answers2

3

The wait-for-typing behavior is a feature of the operating system and shell. They turn your typing into standard input for the JVM, and decide what constitutes end of file and what makes data available to pass to a program that is reading its standard input.

As far as the JVM is concerned, it is just asking for data from standard input, in a way that will block if there is no data available and it is not at end of file. It would be doing the same if standard input were a disk file.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
1

This is implied by the statement that the InputStreamReader has blocking behavior: the reading methods will not return until there is something to be read, or an error occurs.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436