電卓を実装する最も簡単な方法は、再帰を使うことです。
public float calculate(String input) { int pos = input.indexOf('+'); if (pos != -1) { return calculate(input.substring(0, pos)) + calculate(input.substring(pos + 1)); }
コードは最初に+演算子を抽出し、Stringの左部分+ Stringの右部分の結果を返します。 4つのオペランドについても同じプロセスが使用されます。 *および/は、+および -
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