I know i was hoping for something that might work to sovle this problem, but it didnt. What I need to do is make it so the user can type in an expression (ie: "1 + 1", "2 - 1", "1 * 1", "2 / 1") and my program will recognize the expressions and perform the calculation... To my knowlege the part that makes no sence is the "if", "else if" statement part, but I did try!
The error I get is incompatible types @ line 33, 35 (listed twice), 37 (listed twice), and 39 (listed twice).
The String "1 + 1" consists of 5 characters. You read 3 characters, "1", " " and "+" and try to convert each of these to doubles. This is not correct as the 2nd (" ") and last character ("+") can not be converted to a double.
Originally posted by Robert Jan van der Waals: The String "1 + 1" consists of 5 characters. You read 3 characters, "1", " " and "+" and try to convert each of these to doubles. This is not correct as the 2nd (" ") and last character ("+") can not be converted to a double.
The default delimiter for StringTokenizer is whitespace (the space character, the tab character, the newline character, the carriage-return character, and the form-feed character), so the constructor the OP used should work as s/he expected.
I'd like to make some comments on your code that will hopefully assist you.
- review the names of your variables. I would use num1 (for first operand), op (for operator) and num2 (for second operand). Basically replace 'num3' with 'num2' in your code. The variables 'num1' and 'num2' can remain as doubles, delete the num3 reference and define the variable 'op' as String.
- you can choose to keep the s1, s2 and s3 variables - but they are not necessary. If you choose to keep these variables, then the problem you have is the line:
num2 = Double.parseDouble(s2);
In your original code, num2 is supposed to hold the value of the operator after the tokenisation has occurred. It is not a number and therefore does not need to be parsed for a double value. So the line should read:
num2 = s2; (or op = s2; - if you change variable names as suggested).
You can do away with s1, s2 and s3 altogether though and assign num1, op and num2 directly - like so:
num1 = Double.parseDouble(st.nextToken()); op = st.nextToken();
and I'll leave num2 up to you.
- the next matter to correct is how you're checking for the operator. The operator is a String - to compare strings, you need to do something like:
if (op.equals("+")) etc ...
The rest of the if statement should be straightforward from here.
- finally, you need to initialise the variable "result" (to 0 for example) before attempting to assign the result of your calculation.
Hope this proves useful to you - ask more questions if you get stuck.
Regards, JD [ February 21, 2007: Message edited by: John Dell'Oso ]