Home Segments Top Top Previous Next

499: Mainline

You readily can adapt the program in Segment 495 to deal with both numbers and strings. In the following, the value of the nextToken method is assigned to a local variable, next, which is then compared with the TT_NUMBER and TT_WORD instance variables. In the event that the value returned by the nextToken method is the value of the TT_WORD instance variable, the token is ignored. A switch statement, of the sort you learned about in Chapter 26, responds appropriately to the value:

import java.io.*; 
public class Demonstrate { 
 public static void main(String argv[]) throws IOException { 
  FileInputStream stream = new FileInputStream("input.data");  
  InputStreamReader reader = new InputStreamReader(stream); 
  StreamTokenizer tokens = new StreamTokenizer(reader); 
  int next = 0;  
  while ((next = tokens.nextToken()) != tokens.TT_EOF) { 
   switch (next) {  
    case StreamTokenizer.TT_WORD: break;  
    case StreamTokenizer.TT_NUMBER:  
     int x = (int) tokens.nval; 
     tokens.nextToken(); int y = (int) tokens.nval; 
     tokens.nextToken(); int z = (int) tokens.nval; 
     Movie m = new Movie(x, y, z); 
     System.out.println("Rating: " + m.rating());        
     break;  
   }  
  } 
  stream.close(); 
 } 
}