我在使用switch语句和IntBinaryOperator时无法获得输出。我试图用Java构建一个简单的计算器,但我发现IntBinaryOperator减少了不必要的样板代码。希望您能向我展示最佳方法。谢谢。
我写的三个类如下。
package gui_calc;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.function.IntBinaryOperator;
public class CalculatorJFrame extends JFrame implements ActionListener {
static protected JLabel lblOut;
private JButton btnEq;
private JButton btnClear;
public CalculatorJFrame() {
setTitle("CALCULATOR");
JPanel container = new JPanel(); //create a JPanel inside the JFrame as a container
container.setLayout(new BorderLayout());
//add your components in here
lblOut = new JLabel("");
btnEq = new JButton("=");
btnClear = new JButton("C");
btnEq.addActionListener(this);
btnClear.addActionListener(this);
NumButtonsJP numBtns = new NumButtonsJP(); //create an instance of NumButtonsJP
OpButtonsJP opBtns = new OpButtonsJP(); //create an instance of OpButtonsJP
container.add(btnClear, BorderLayout.WEST);
container.add(btnEq, BorderLayout.EAST);
container.add(lblOut, BorderLayout.NORTH);
container.add(numBtns, BorderLayout.CENTER); //add the numBtns JPanel to the container
container.add(opBtns, BorderLayout.SOUTH); //add the opBtns JPanel to the container
add(container); //add container to the JFrame
}
static protected void updateOutLabel(String suffix) {
String currLblContent = lblOut.getText().trim(); //get current content of lblOut
lblOut.setText(currLblContent + suffix); //update the output label on the main container
}
static protected void clearOutLabel() {
lblOut.setText("");
}
@Override
public void actionPerformed(ActionEvent e) {
String face = e.getActionCommand().trim();
switch (face) {
case "=":
//do math... get the values... and reset the label with the result
updateOutLabel("=" + getResultFromQuestion(lblOut.getText()));
break;
case "+":
IntBinaryOperator add = (a,b) -> a + b;
System.out.println("Your answer is" + (add));
break;
case "-":
IntBinaryOperator substract = (a, b) -> a - b;
System.out.println("Your answer is" + (substract.applyAsInt(lblOut.getText().charAt(0),lblOut.getText().charAt(1))));
break;
case "*":
IntBinaryOperator multiply = (a, b) -> a * b;
System.out.println("Your answer is" + (multiply));
break;
case "/":
IntBinaryOperator divide = (a, b) -> a / b;
System.out.println("Your answer is" + divide);
case "C":
clearOutLabel();
break;
}
}
private String getResultFromQuestion(String text) {
double resultStr = 10;
return "" + resultStr;
}
public static void main(String[] args) {
//create instance of calculator and run it
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CalculatorJFrame calcGUI = new CalculatorJFrame();
calcGUI.setDefaultCloseOperation(calcGUI.EXIT_ON_CLOSE);
calcGUI.setSize(300, 300);
calcGUI.setVisible(true);
}
});
}
package gui_calc;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class OpButtonsJP extends JPanel implements ActionListener{
JButton btnAdd = new JButton("+");
JButton btnSub = new JButton("-");
JButton btnMul = new JButton("*");
JButton btnDiv = new JButton("/");
JButton [] opsBtns = {btnAdd, btnSub, btnMul, btnDiv};//array of jbuttons
public OpButtonsJP(){
setLayout(new GridLayout(1,4));
for(int i=0; i<opsBtns.length; i++){
add(opsBtns[i]); //add the button to the JPanel
opsBtns[i].addActionListener(this); //add the ActionListener to make the button functional
}
}
@Override
public void actionPerformed(ActionEvent e) {
String face = e.getActionCommand();
System.out.println(face + " was clicked");
CalculatorJFrame.updateOutLabel(face);
//String currLblContent = CalculatorJFrame.lblOut.getText();
//CalculatorJFrame.lblOut.setText(currLblContent + face); //update the output label on the main container
}
}
package gui_calc;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class NumButtonsJP extends JPanel implements ActionListener {
JButton numButtons[];
public NumButtonsJP() {
setLayout(new GridLayout(4, 3));
numButtons = new JButton[10];
for (int i = 1; i < 10; i++) {
//create a JButton with the number on its face and add it to the array of JButtons
numButtons[i] = new JButton("" + i);
numButtons[i].addActionListener(this); //make the button trigger the event
//add the JButton to the JPanel
add(numButtons[i]);
}
JLabel spaceHolder = new JLabel(); //create the spaceHolder as a blank label
add(spaceHolder); //add the spaceHolder to the JPanel
numButtons[0] = new JButton("0"); //create the Zero button
numButtons[0].addActionListener(this);//make the Zero button trigger actioNPerformed
add(numButtons[0]); //add the Zero button to the JPanel
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String face = e.getActionCommand();
System.out.println(face + " was clicked");
int num = Integer.parseInt(face.trim()); // parse to an int so we can use in math
CalculatorJFrame.updateOutLabel(face);
//String currLblContent = CalculatorJFrame.lblOut.getText();
//CalculatorJFrame.lblOut.setText(currLblContent + face); //update the output label on the main container
}
}
最佳答案
我稍微修改一下您的代码,基本上我要添加一个表达式评估器。
UI基本上构造了表达式,并传递给您的getResultFromQuestion()函数,该函数接受输入,然后尝试解析为数学函数。
您必须正确处理异常,这会破坏BinaryOperators,因为您可以输入两个以上的操作数。
@Override
public void actionPerformed(ActionEvent e) {
String face = e.getActionCommand().trim();
switch (face) {
case "=":
// do math... get the values... and reset the label with the result
updateOutLabel("=" + getResultFromQuestion(lblOut.getText()));
break;
case "C":
clearOutLabel();
break;
}
}
private String getResultFromQuestion(String text) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = null;
try {
result = engine.eval(text);
} catch (ScriptException e) {
//Do something with the exception
}
return result.toString();
}