The easiest way to implement a calculator is to use recursion.
public float calculate(String input) {
int pos = input.indexOf('+');
if (pos != -1) {
return calculate(input.substring(0, pos)) + calculate(input.substring(pos + 1));
}
The code first extracts the + operator and returns the result of the left part of the String + the right part of the String. The same process is used for the 4 operands. * and / must be processed last as they have priority over + and -
public class Calculator {
public float calculate(String input) {
int pos = input.indexOf('+');
if (pos != -1) {
return calculate(input.substring(0, pos)) + calculate(input.substring(pos + 1));
} else {
pos = input.indexOf('-');
if (pos != -1) {
return calculate(input.substring(0, pos)) - calculate(input.substring(pos + 1));
} else {
pos = input.indexOf('*');
if (pos != -1) {
return calculate(input.substring(0, pos)) * calculate(input.substring(pos + 1));
} else {
pos = input.indexOf('/');
if (pos != -1) {
return calculate(input.substring(0, pos)) / calculate(input.substring(pos + 1));
}
}
}
}
String toProcess = input.trim();
if( toProcess == null || toProcess.isEmpty() )
return 0;
return Float.parseFloat(toProcess);
}
public static void main(String[] argv) {
Calculator calculator = new Calculator();
String input;
float output;
input = " 2 + 2 ";
output = calculator.calculate(input);
System.out.println(input + " = " + output);
input = " 1 + 2 * 3";
output = calculator.calculate(input);
System.out.println(input + " = " + output);
input = " 1 * 2 + 3";
output = calculator.calculate(input);
System.out.println(input + " = " + output);
input = " 1 / 2 * 3";
output = calculator.calculate(input);
System.out.println(input + " = " + output);
input = " 1 + 2 * 3 - 1/2";
output = calculator.calculate(input);
System.out.println(input + " = " + output);
input = " - 1/2 + 1 + 2 * 3 ";
output = calculator.calculate(input);
System.out.println(input + " = " + output);
input = "1+2*3+4*5*6+7*8*9*10";
output = calculator.calculate(input);
System.out.println(input + " = " + output); //--> 5167
input = " 12345678+1";
output = calculator.calculate(input);
System.out.println(input + " = " + output); //--> 12345679
}
}
2 + 2 = 4.0 1 + 2 * 3 = 7.0 1 * 2 + 3 = 5.0 1 / 2 * 3 = 1.5 1 + 2 * 3 - 1/2 = 6.5 - 1/2 + 1 + 2 * 3 = 6.5 1+2*3+4*5*6+7*8*9*10 = 5167.0 12345678+1 = 1.2345679E7
java.util.concurrent.Executors
java.util.concurrent.CountDownLatch