Link to home
Start Free TrialLog in
Avatar of AnthonyCosenza
AnthonyCosenza

asked on

StringTokenizer not printing last item in expression


I hav something like this

while (st.hasMoreTokens( )) {
    if ( !token.matches("[0-9\\(\\)\\+\\-\\*/]+") ) {
        System.err.println("INVALID EXPRESSION");
        System.exit(1);
    } else {
        System.out.println(token);
        token = st.nextToken( );
    }
}
System.exit(1);

Where i hav a StringTokenizer goin through the string which is in a file...
What happens here is if i hav a expression in the file, for example ( 4 + 3 )..
it prints:

(
4
+
3

.. It doesnt print watever the last item is...

Puzzled..
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

How are you creating the tokenizer?
Avatar of AnthonyCosenza
AnthonyCosenza

ASKER

while (line != null) {

    String token;
    StringTokenizer st = new StringTokenizer(line);
                  
    // Set token to be the first of item in the String
    token = st.nextToken();
....
}

like so..
Can you post what's in the line here please?
FileReader fr = new FileReader("expression.txt");
BufferedReader br = new BufferedReader(fr);
            
// Create a String to store the contents of the file
String line = br.readLine( );


Thats it... line is wat is read from the file.. which is ( 4 + 3 ) for example..
The following will give you an array of atoms

String[] atoms = line.split("[0-9\\(\\)\\+\\-\\*/]");
I dont want an array... i want to kno why i'm not getting the last "atom" with the string tokenizer the way i am doin it...
Because you call this:

>>token = st.nextToken( );

as the last line in your loop, which advances the 'pointer' and you do nothing with it
I thought you might want the atoms - that's why i suggested the split thing. Have you got the  thing about nextToken?
ok, if i remove that line it just prints the first "atom" out continuously...

What can i do to stop this and get all the values in the expressions..
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
8-)