用JAVA判断输入的公式

2024-12-17 19:22:35
推荐回答(1个)
回答1:

import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;import javax.swing.JButton;
import javax.swing.JTextField;@SuppressWarnings("serial")
public class Calc extends Frame{

public static final int WIN_HEIGHT = 321;
public static final int WIN_WIDTH = 228;

private JTextField calcText = new JTextField("0");

String[] inStr = new String[] {"(", ")", "D", "+",
"7", "8", "9", "-",
"4", "5", "6", "*",
"1", "2", "3", "/",
"0", ".", "C", "="};

public void init() {
this.setSize(WIN_WIDTH, WIN_HEIGHT);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setLayout(null);
this.setTitle("Calc");

calcText.setVisible(true);
calcText.setHorizontalAlignment(JTextField.RIGHT);
this.add(calcText);
calcText.setBounds(20, 40, 190, 25);

//创建btn
JButton btn;
for(int i = 1, j = 0; i <= inStr.length; i++) {
btn = new JButton(inStr[i-1]);
this.add(btn);
btn.addMouseListener(new MyMouse());

btn.setBounds(20 + (45 + 3) * ((i-1) % 4), 70 + (43 + 2) * j, 45, 43);

if(i % 4 == 0) {
j++;
}

}

}

class MyMouse extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
JButton btn = (JButton)e.getSource();
String action = btn.getText();
if("C".equals(action)) {
calcText.setText("");
} else if("D".equals(action)) {
String str = calcText.getText();
calcText.setText(str.substring(0, str.length() - 1));
} else if("=".equals(action)) {
try {
calcText.setText(separate(calcText.getText()) + "");
} catch (Exception e1) {
calcText.setText("式子错误");
}
} else {
calcText.setText(calcText.getText() + action);
}
}
}

public static void main(String[] args) {

new Calc().init();
}

//拆除括号进行计算
public double separate(String str) throws Exception {
double re = 0;
System.out.println(str);
//如果不存在括号,进行直接计算
if( ( !str.contains("(")) && (!str.contains(")") ) ) {
re = calculate(str);
} else {
//若有括号,继续进一步拆解括号计算
String oldStr = extract(str);
String newStr = calculate(extract(str)) + "";
re = separate(str.replace(oldStr, strValue(Double.parseDouble(newStr))));
}

return re;
}
private String strValue(Double d) {
if(d % 1 == 0) {
return ""+d.intValue();
}
return d.toString();
}

//拆解括号
public String extract(String str) throws Exception {

String childStr = str.substring(str.indexOf('(') + 1, str.length());
if(!childStr.contains("(")) {
return str.substring(str.indexOf('(') , str.indexOf(')') + 1);
}
if(childStr.indexOf('(') - childStr.indexOf(')') > 0) {
return str.substring(str.indexOf('(') , str.indexOf(')') + 1);
} else {
return extract(childStr);
}

}

//无括号表达式直接计算
public double calculate(String str) {
double re = 0;
Formula f = new Formula(str);
if(f.hasAction()) {
re += calculate(f.toString());
} else {
re += Double.parseDouble(f.toString());
}
return re;
}

class Formula {
private List strList = new ArrayList();
private List doubleList = new ArrayList();
private char action = '0';
private String sourceStr;

public Formula(String str) {
str = str.trim().replace("(", ")").replace(")", " ").replace(" ", "") ;
sourceStr = str;

char[] chars = str.toCharArray();
String num = "";
for(char c : chars) {
//非数字和.
if((c < 48 || c > 57) && c != 46) {
strList.add(c);
setAction(c);
doubleList.add(Double.parseDouble(num));
num = "";
} else {
num += c;
}
}
if(!"".equals(num)) {
doubleList.add(Double.parseDouble(num));
}
}

public boolean hasAction() {
return action != '0';
}

public void setAction(char c) {
if(action == '0') {
action = c;
return;
}
if((action == '/' || action == '*')) {
return;
} else if(c == '*' || c=='/') {
action = c;
}

}

public String toString() {
if(!hasAction()) {

return sourceStr;
}
int index = strList.indexOf(action);
double num1 = doubleList.get(index);
double num2 = doubleList.get(index+1);

switch(action) {
case '+':
return sourceStr.replace(strValue(num1) + action + strValue(num2), strValue(num1+num2) + "");
case '-':
return sourceStr.replace(strValue(num1) + action + strValue(num2), strValue(num1-num2) + "");
case '*':
return sourceStr.replace(strValue(num1) + action + strValue(num2), strValue(num1*num2) + "");
case '/':
return sourceStr.replace(strValue(num1) + action + strValue(num2), strValue(num1/num2) + "");
case '0':
return sourceStr;
}
return sourceStr;

}

}}
我也没有详细的测。你测试一下,如果式子是错误的会在文本框输出 式子错误。控制台会输出 计算 步骤。功能算是实现了,再有什么问题直接QQ叫我好了。