我正在自学Java,而不是通常的"hello World!"我认为最好是构建一个计算器应用程序,并在构建它的同时学习Java。
"JavaCalculator.png"我的问题是:我如何编程"("one_answers")"括号键,以便我可以在计算器应用程序中使用它们。
一个典型的数字按钮(2)在我的应用程序是:
private void btnTwoActionPerformed(java.awt.event.ActionEvent evt) {
if (bFinish == false) {
String btnTwoText = txtDisplay.getText() + btnTwo.getText();
dObtainer = Double.parseDouble(btnTwoText);
txtDisplay.setText(btnTwoText);
} else {
txtDisplay.setText("");
String btnTwoText = txtDisplay.getText() + btnTwo.getText();
dObtainer = Double.parseDouble(btnTwoText);
txtDisplay.setText(btnTwoText);
bFinish = false;
}
}
一个典型的操作数按钮(-)在我的应用程序是:
private void btnMinusActionPerformed(java.awt.event.ActionEvent evt) {
String button_text = "-";
getOperator(button_text);
}
private void getOperator(String btnText) {
mathOperator = btnText.charAt(0);
dTotal1 = dTotal1 + dObtainer;
txtDisplay.setText("");
}
这是当"Equals"按钮被按下时的结果。
private void btnEqualsActionPerformed(java.awt.event.ActionEvent evt) {
String sBuffer = "";
switch (mathOperator) {
case '+':
dResult = dTotal1 + dObtainer;
break;
case '-':
dResult = dTotal1 - dObtainer;
break;
case '/':
dResult = dTotal1 / dObtainer;
break;
case '*':
dResult = dTotal1 * dObtainer;
break;
case '^':
dResult = Math.pow(dTotal1, dObtainer);
break;
case '(':
sBuffer = "(";
//dResult = dObtainer;
break;
}
mathOperator = ' ';
dTotal1 = 0;
dObtainer = 0;
DecimalFormat df = new DecimalFormat("#.########");
if(!"(".equals(sBuffer))
sBuffer = df.format(dResult);
if(!")".equals(sBuffer))
sBuffer = df.format(dResult);
sBuffer = sBuffer.replace(".0", "");
txtDisplay.setText(sBuffer);
bFinish = true;
}
作为初学者,我建议使用内置的Javascript引擎
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "4+5+(8*4)"; //replace your expression here
System.out.println(engine.eval(foo));
另一个可以用MVEL
您可以使用StringBuilder
创建表达式(如2+(1-5)
),然后使用:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
...
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String exp = sb.toString(); //sb is the string builder
int result = 0;
try {
result = (int) engine.eval(exp);
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//from here you can use result in whatever way you want