public class FormattedInput
1: //FormattedInput.java
2:
3: import java.io.*;
4:
5: public class FormattedInput
6: {
7: //Object to tokenize input from the standard input stream
8: private StreamTokenizer tokenizer =
9: new StreamTokenizer(new InputStreamReader(System.in));
10:
11: //Method to read an int value
12: public int intRead()
13: {
14: try
15: {
16: for (int i=0; i<5; i++)
17: {
18: if (tokenizer.nextToken() == tokenizer.TT_NUMBER)
19: //Value is numeric, so return as int
20: return (int)tokenizer.nval;
21: else
22: {
23: System.out.println("Incorrect input: " +
24: tokenizer.sval +
25: " Re-enter an integer");
26: continue; //Retry the read operation
27: }
28: }
29: System.out.println("Five failures reading an int value" +
30: " - program terminated");
31: System.exit(1); //End the program
32: return 0;
33: }
34: catch(IOException e) //Error reading in nextToken()
35: {
36: System.out.println(e); //Output the error
37: System.exit(1); //End the program
38: return 0;
39: }
40: }
41:
42: //Read a string
43: public String stringRead()
44: {
45: try
46: {
47: for (int i=0; i<5; i++)
48: {
49: int tokenType = tokenizer.nextToken(); //Read a token
50: //if type is a string, return it
51: if (tokenType == tokenizer.TT_WORD || tokenType == '\"')
52: return tokenizer.sval;
53: else if (tokenType == '!') //Non-alpha returned as type
54: return "!"; //so return end string
55: else
56: {
57: System.out.println("Incorrect input. " +
58: "Re-enter a string between double quotes");
59: continue; //Retry the read operation
60: }
61: }
62: System.out.println("Five failures reading a string" +
63: " - program terminated");
64: System.exit(1); //End the program
65: return null;
66: }
67: catch(IOException e)
68: { //Error reading in nextToken()
69: System.out.println(e); //Output the error
70: System.exit(1); //End the program
71: return null;
72: }
73: }
74: }
75: