Math program problem. Can I have a bit of help please :D
Hi, so, I am currently doing a Math type program. Basically, I want it to open up a text file, inside the file, it has simple math calculations, like:
4 + 2
3 * 2
5 / 5
So, I want it to solve these equations. I know, I have to read the file, line by line, loop it, and split the line into x, y and the operator. It will then do the calculations, by testing if it is certain operators. Then it will output the original problem, and the answer.
But, what I currently have, is not working. All the answers are coming out as 0, so I dunno what I have done wrong. Here is the code.
Code:
import java.io.*;
class Calculator {
public static void main(String args[]){
int z = 0;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:/Test1.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] Parts = strLine.split(" ");
String op = Parts[1];
int x = Integer.parseInt(Parts[0]);
int y = Integer.parseInt(Parts[2]);
{
if(op == "+"){
z = x + y;
}
else if(op == "-"){
z = x - y;
}
else if(op == "/"){
z = x / y;
}
else if (op == "*"){
z = x * y;
}
System.out.println(x + " " + op + " " + y + " = " + z);
}
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Any help will be appreciated. It is not displaying any errors, I have probably just made a really stupid mistake :p
Re: Math program problem. Can I have a bit of help please :D
You should use equals instead of ==
op.equals("+"),.... and so on...
Re: Math program problem. Can I have a bit of help please :D
Quote:
Originally Posted by
SRaith
You should use equals instead of ==
op.equals("+"),.... and so on...
OMG, yay. Thanks soo much. Works. Wow. Spent ages, looking at everything, except that one part. Woops.:(blush):