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("INVALI
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..
How are you creating the tokenizer?
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..
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?
ASKER
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..
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\\(\\)\\+\ \-\\*/]");
String[] atoms = line.split("[0-9\\(\\)\\+\
ASKER
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
>>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?
ASKER
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..
What can i do to stop this and get all the values in the expressions..
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
8-)