0

I'm doing homework for my data structures class and ran into a snag at a certain point. Basically, I have an expression like

(varx + vary*varz[(vara+varb[(a+b)*33])])/55

and I have to store the variables in the equation in either of two arraylists, scalar (for simple variables) or arrays (for variables with arrays). In this example, variables like varx or vary would go into the scalar array and varz would be an array because it has a bracket following it right after in the expression. I know StringTokenizer makes the scalar variables easy to track when I use the code..

StringTokenizer st = new StringTokenizer(expr, " \t*+-/()[]");

However, this doesn't really work for being able to tell what the arrays variable is since it also erases the brackets since the answer that would return if I were to print it is

while(st.hasMoreTokens()){
    System.out.println(st.nextToken());
}

and it would print

varx
vary
varz
vara
varb
a
b
33
55

How would I be able to check for a bracket after each variable to tell if it should go in the scalar arraylist or the arrays arraylist? Thanks for the help!

nobalG
  • 4,544
  • 3
  • 34
  • 72
  • Not an answer, but according to the Javadoc for `StringTokenizer`, "... StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code..." – Dawood ibn Kareem Oct 08 '14 at 05:00
  • 1
    You must remove the brackets from the list of delimiters - since the tokenizers removes all the delimiters, but you need them. I'd suggest you either parse it character at a time, or use a regular expression. (You can write your own version of StringTokenizer which would preserve the delimiters as separate items in the resulting array). BTW, you will also need to preserve the operators. – joeking Oct 08 '14 at 05:05
  • Exactly. You're using the wrong tool for this job. You need to write yourself a proper scanner, and I don't mean java.util.Scanner. – user207421 Oct 08 '14 at 06:09
  • Yeah, figured that out after a while. I created a loop to go through each character, and a new string for each variable to sort them into scalar or arrays depending if it had a bracket next to it. Thanks for the help =) – farris awadallah Oct 08 '14 at 23:19

0 Answers0