Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Text Input Java Calculator Help

Hi All,
Very new programmer here... 4 days in now.

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! :)

Please Help!!

/**
*The CalculatorApp class reads the users input and calculates primitive
*arithmetic expressions.
*
*Author: Evan Cristofori
*Date: 02/21/07
*
*/
import java.io.*;
import java.util.*;
class CompoundCalculator {
public static void main(String[] args)
throws java.io.IOException {

String inputString;
String s1, s2, s3;
double num1, num2, num3, result;

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

System.out.println("What do you want to compute? ");
inputString = br.readLine();

StringTokenizer st = new StringTokenizer(inputString);
s1 = st.nextToken();
s2 = st.nextToken();
s3 = st.nextToken();

num1 = Double.parseDouble(s1);
num2 = Double.parseDouble(s2);
num3 = Double.parseDouble(s3);

if (num2 = "+")
result = num1 + num3;
else if (num2 = "-")
result = num1 - num3;
else if (num2 = "*")
result = num1 * num3;
else if (num2 = "/")
result = num1 / num3;

System.out.println("The result is: " + result);
}
}

The error I get is incompatible types @ line 33, 35 (listed twice), 37 (listed twice), and 39 (listed twice).

Thanks
[1868 byte] By [ev4n7] at [2007-11-11 10:26:14]
# 1 Re: Text Input Java Calculator Help
You put num2 as double:
double num1, num2, num3, result;

later you're asking if it is :
if (num2 = "+")
num2 is double and it could not be + nor -.....

I would od this :
if (num2 instanceof double)
this means that num2 IS NOT + nor -...
then do..
Good luck,
Kinda Electroni at 2007-11-11 22:31:35 >
# 2 Re: Text Input Java Calculator Help
the compilation error is in the if condition..
change the code to
if(num2 == "+")
Still the program will not compile. Becuase in the condition check is on incomparable types. You are comparing a double value with a String ("+").
Double.parseDouble() will return premitive double.Which means you are calling parseDouble() method on "+" operator. That will throw a RuntimeException called NumberFormatException
so do the following changes in your program..
remove
num2 = Double.parseDouble(s2); from your code.(Since operator is a String you don't want to do that)
change the if condition as follows
if (s2.trim().equals("+"))
result = num1 + num3;
else if (s2.trim().equals("-"))
result = num1 - num3;

.....
sudheerprem at 2007-11-11 22:32:30 >