Reputation: 503
i have no idea why i am not getting the expected results! I have written the expected result in the end. Alright, i have two classes: CalculatorEngine
and CalculatorInput
, the former calculates while the latter gives a line mode interface. The code for CalculatorEngine
goes like this, nothing fancy:
public class CalculatorEngine {
int value;
int keep;
int toDo;
void binaryOperation(char op){
keep = value;
value = 0;
toDo = op;
}
void add() {binaryOperation('+');}
void subtract() {binaryOperation('-');}
void multiply() {binaryOperation('*');}
void divide() {binaryOperation('/');}
void compute() {
if (toDo == '+')
value = keep + value;
else if (toDo == '-')
value = keep - value;
else if (toDo == '*')
value = keep * value;
else if (toDo == '/')
value = keep/value;
keep = 0;
}
void clear(){
value = 0;
keep = 0;
}
void digit(int x){
value = value*10 + x;
}
int display(){
return (value);
}
CalculatorEngine() {clear();} //CONSTRUCTOR METHOD!
}
And the code for CalculatorInput
goes like this:
import java.io.*;
public class CalculatorInput {
BufferedReader stream;
CalculatorEngine engine;
CalculatorInput(CalculatorEngine e) {
InputStreamReader input = new InputStreamReader(System.in);
stream = new BufferedReader(input);
engine = e;
}
void run() throws Exception {
for (;;) {
System.out.print("[" +engine.display()+ "]");
String m = stream.readLine();
if (m==null) break;
if (m.length() > 0) {
char c = m.charAt(0);
if (c == '+') engine.add();
else if (c == '*') engine.multiply();
else if (c == '/') engine.divide();
else if (c == '-') engine.subtract();
else if (c == '=') engine.compute();
else if (c == '0' && c <= '9') engine.digit(c - '0');
else if (c == 'c' || c == 'C') engine.clear();
}
}
}
public static void main(String arg[]) throws Exception{
CalculatorEngine e = new CalculatorEngine();
CalculatorInput x = new CalculatorInput(e);
x.run();
}
}
I expect the answer to be like this:
[0]1
[1]3
[13]+
[0]1
[1]1
[11]=
[24]
BUT i am getting this:
[0]1
[0]3
[0]+
[0]1
[0]1
[0]+
[0]
Seems like digit
function isn't working properly. Help!
Upvotes: 0
Views: 504
Reputation: 4640
else if (c == '0' && c <= '9') engine.digit(c - '0');
if c not equals 0 its false..
Upvotes: 2
Reputation: 5920
Change this:
if (c == '0' && c <= '9')
To this:
if (c >= '0' && c <= '9')
Otherwise, it will only be true when c is '0'
.
Upvotes: 4