0

As part of a calulator program I am writing, I am required to have the user input all the parameters in one string and I need to extract the corresponding values from it.

For example the user enters "3 5 *" he'll get "15" back.

So the program I need to write will take '3' and assign that to double input1, '5' to double input2, and '*' to char operator. How do I get java to assign parts of a string to different members.

I was thinking of maybe splitting the user's string into multiple strings and parsing the values out but I don't know how effective that would be. Thanks in advance.

3 Answers3

0

You will need to consider the order of operations if you have more then one operation. IE (3 4 +) 3 *. A common method for this would be to use a stack. Push the values onto the stack and perform the operation on the values you pop following the operation itself. For parsing simply split on the space ' '. However if you have more complex expressions consider a post order traversal, or stack implementation.

SJP
  • 1,330
  • 12
  • 21
  • Okay but if I did this, how do I make sure Java knows when the next value is a double or char? Sorry I'm just starting Java, and I'm still not sure about some transitions between this and C. – user3300735 May 01 '14 at 01:28
0

This question has already been answered here: Evaluating a math expression given in string form

I gave a very simple breakdown in my answer here as well: Calculating String-inputed numerical expressions?

Community
  • 1
  • 1
  • None of the answers to the first linked question are applicable here. Neither is your answer to the second linked question. – Dawood ibn Kareem May 01 '14 at 01:03
  • I disagree. The user's question is on the methodology, not the procedure for his hypothesis on the methodology. General tokenization doesn't account for operator presidence. – Mikeologist May 01 '14 at 01:23
0

You can use the StringTokenizer to split the string wherever it finds a space.

String s = "3 5 *"; StringTokenizer st = new StringTokenizer(s);

You can check if there are more tokens via st.hasMoreTokens(). You can use the token aka string via st.nextToken() (it returns a string).

You can also cast each "string" such as the "3" into a double via: String firstNumString = "3"; Double first = Double.parseDouble(firstNumString);

This results in the Double variable 'first' containing the number 3.

Sterls
  • 723
  • 12
  • 22
  • From the `StringTokenizer` Javadoc - "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code." – Dawood ibn Kareem May 01 '14 at 01:02