如何在java中實現一個計算器

實現一個計算器最簡單的方法是使用遞歸。

句法:

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個操作數使用相同的過程。 *和/必須最後處理,因為他們優先於+和 -

創建以下java文件:

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

最近評論