// Program: 4033 // Author: Manuel J. A. Eugster ( e0126312@student.tuwien.ac.at ) // FileId: $Id: Scanner.java,v 1.1 2002/01/14 17:28:09 heder Exp $ package Wider; import java.lang.*; // CLASS: // Lexical analysis of a string. // Maybe better to extend class java.io.StreamTokenizer. // public class Scanner implements Token { public int valueTok; // Token public int valueNum; // If token is a number, it is saved here private int pos; // Actual position private int resistorCount; // Actual count of resistors private StringBuffer expr; // Input expression // METHOD: // Constructor. // public Scanner( StringBuffer expr ) throws ScannerException { this.expr = expr; this.pos = -1; this.valueNum = 0; this.valueTok = 0; this.resistorCount = 0; nextToken(); // Provide first token } // METHOD: // Provides next token from input string. // Kind of token is saved and provided in valueTok, // if it's a number, it's saved and provided in // valueNum. // public void nextToken() throws ScannerException { String num = new String(); char c = 0; valueNum = 0; // Delete last num value pos++; // Check position // if ( pos >= expr.length() ) { valueTok = EOL; return; } // Check next token // switch ( ( c = expr.charAt( pos ) ) ) { case T_BRO: { valueTok = T_BRO; return; } case T_BRC: { valueTok = T_BRC; return; } case T_SER: { valueTok = T_SER; return; } case T_PAR: { valueTok = T_PAR; return; } default: // All other things (resistor values) { // Get all chars until the next token // while ( c != T_BRO && c != T_PAR && c != T_SER && c != T_BRC && pos < expr.length() ) { num += c; pos++; if ( pos < expr.length() ) { c = expr.charAt( pos ); } } pos--; // Because of the incremention above // Semantic check // try { valueNum = Integer.parseInt( num ); } catch ( NumberFormatException e ) { throw new ScannerException( "Bad resistor value" ); } // Count check // if ( ( resistorCount++ ) >= MAX_RES ) { throw new ScannerException( "Too much resistors" ); } valueTok = T_NUM; return; } } } }