学java的时候自己编的,很简单,能够连续输入计算式后进行计算
成都创新互联长期为1000+客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为临颍企业提供专业的成都网站建设、网站制作,临颍网站改版等技术服务。拥有10余年丰富建站经验和众多成功案例,为您定制开发。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**简易计算器,能够进行简单的计算
*
* @see 2008.12.9
*/
public class CalculatorA
implements ActionListener{
private JFrame frame;
private JTextField field;
private JButton[] allButtons;
private JButton clearButton;
// private JButton backButton;
String result="";//保存结果
StringBuilder sb = new StringBuilder();//保存要进行的计算式
int x = 0; //用来判断上一次的事件类型
String str = "123+456-789*0.=/";
ArrayListString arrayList = new ArrayListString();//保存计算式,通过方法进行运算
public CalculatorA(){
frame = new JFrame("我的计算器v1.1");
frame.setLocation(300,300);
field = new JTextField(25);
allButtons = new JButton[16];
for(int i=0;iallButtons.length;i++){
allButtons[i]= new JButton(str.substring(i,i+1));
}
clearButton = new JButton("CLEAR");
// backButton = new JButton("——");
init();
setFondAndColor();
addEventHander();
}
public void init(){
frame.setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(field);
for(int i=0;iallButtons.length;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
//southPanel.add(backButton);
frame.add(northPanel,BorderLayout.NORTH);
frame.add(centerPanel,BorderLayout.CENTER);
frame.add(southPanel,BorderLayout.SOUTH);
}
//设置输入字体
public void setFondAndColor(){
field.setFont(new Font("宋体",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
field.setForeground(Color.RED);
//设置字体从右起始
field.setHorizontalAlignment(JTextField.RIGHT);
}
public void showMi(){
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void addEventHander(){
for(int i=0;iallButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
// backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得当前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //当x为0时表示还没有进行输入
result=str;
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 1){
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 2){
sb.delete(0,sb.length());
result = result+str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 3){
result = str;
sb.delete(0,sb.length());
arrayList.clear();
field.setText(str);
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
result = str;
sb.append(str);
field.setText(str);
x = 1;
}
else{
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
}
else if("+*-/".indexOf(str)!=-1){
if(x == 0){
field.setText("");
x = 2;
}
else if(x == 1){
result = result + str;
arrayList.add(sb.toString());
arrayList.add(str);
sb.append(str);
field.setText(result);
x = 2;
}
else if(x == 2){
x = 2;
}
else if(x == 3){
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 2;
}
else{
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
}
else if("=".equals(str)){
if(x == 0){
field.setText("0");
arrayList.clear();
result = "0";
x = 3;
}
else if(x == 1){
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
else if(x == 2){
field.setText("数据格式错误.....");
arrayList.clear();
x = 0;
}
else if(x == 3){
field.setText(result);
x = 3;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 3;
}
else {
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
}
else if("CLEAR".equals(str)){
arrayList.clear();
field.setText("0");
arrayList.add("0");
x = 4;
}
else{
if(result.length()1){
result = result.substring(0,result.length()-1);
if(sb.length()0){
sb.delete(sb.length()-1,sb.length());
}
else {
sb.delete(0,1);
}
field.setText(result);
x = 5;
}
else{
result = "";
sb.delete(0,sb.length());
arrayList.clear();
field.setText("0");
x = 0;
}
}
}
public static ArrayListString getResult(ArrayListString list){
String res = null;
String[] s = {"/","*","-","+"};
int i=0;
if(list.size()1){
for(;is.length;){
if(s[i].equals("/")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j+1)));
//本地的数据格式
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("*")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("-")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getNumberInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else {
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))+Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
}
}
return list;
}
//对数字字符串进行排除不必要符号
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;kc.length;k++){
c[k] = res.charAt(k);
}
for(int k=0;kc.length;k++){
if((c[k]= '0' c[k]= '9')|| c[k] == '.'){
s_temp += c[k];
}
}
return s_temp;
}
public static void main(String[] args){
new CalculatorA().showMi();
}
}
然后 通过输入 显示结果,比如说:
以下是上图计算器的代码:
package Computer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Count extends JApplet implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField textField = new JTextField("请输入");
String operator = "";//操作
String input = "";//输入的 式子
boolean flag = true;
// boolean flag1 = true;
// boolean flag2 = true;
public void init()//覆写Applet里边的init方法
{
Container C = getContentPane();
JButton b[] = new JButton[16];
JPanel panel = new JPanel();
C.add(textField, BorderLayout.NORTH);
C.add(panel,BorderLayout.CENTER);
panel.setLayout(new GridLayout(4, 4,5,5));
String name[]={"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};//设置 按钮
for(int i=0;i16;i++)//添加按钮
{
b[i] = new JButton(name[i]);
b[i].setBackground(new Color(192,192,192));
b[i].setForeground(Color.BLUE);//数字键 设置为 蓝颜色
if(i%4==3)
b[i].setForeground(Color.RED);
b[i].setFont(new Font("宋体",Font.PLAIN,16));//设置字体格式
panel.add(b[i]);
b[i].addActionListener(this);
}
b[13].setForeground(Color.RED);//非数字键,即运算键设置为红颜色
b[13].setForeground(Color.RED);
}
public void actionPerformed(ActionEvent e)
{
int cnt = 0;
String actionCommand = e.getActionCommand();
if(actionCommand.equals("+")||actionCommand.equals("-")||actionCommand.equals("*") ||actionCommand.equals("/"))
input +=" "+actionCommand+" ";//设置输入,把输入的样式改成 需要的样子
else if(actionCommand.equals("C"))
input = "";
else if(actionCommand.equals("="))//当监听到等号时,则处理 input
{
input+= "="+compute(input);
textField.setText(input);
input="";
cnt = 1;
}
else
input += actionCommand;//数字为了避免多位数的输入 不需要加空格
if(cnt==0)
textField.setText(input);
}
private String compute(String input)//即1237 的 样例
{
String str[];
str = input.split(" ");
StackDouble s = new StackDouble();
double m = Double.parseDouble(str[0]);
s.push(m);
for(int i=1;istr.length;i++)
{
if(i%2==1)
{
if(str[i].compareTo("+")==0)
{
double help = Double.parseDouble(str[i+1]);
s.push(help);
}
if(str[i].compareTo("-")==0)
{
double help = Double.parseDouble(str[i+1]);
s.push(-help);
}
if(str[i].compareTo("*")==0)
{
double help = Double.parseDouble(str[i+1]);
double ans = s.peek();//取出栈顶元素
s.pop();//消栈
ans*=help;
s.push(ans);
}
if(str[i].compareTo("/")==0)
{
double help = Double.parseDouble(str[i+1]);
double ans = s.peek();
s.pop();
ans/=help;
s.push(ans);
}
}
}
double ans = 0d;
while(!s.isEmpty())
{
ans+=s.peek();
s.pop();
}
String result = String.valueOf(ans);
return result;
}
public static void main(String args[])
{
JFrame frame = new JFrame("Count");
Count applet = new Count();
frame.getContentPane().add(applet, BorderLayout.CENTER);
applet.init();//applet的init方法
applet.start();//线程开始
frame.setSize(350, 400);//设置窗口大小
frame.setVisible(true);//设置窗口可见
}
}
简单写了下,代码如下请参照:
/**
* 计算器类
*
* @author Administrator
*
*/
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 3868243398506940702L;
// 文本框
private JTextField result;
// 按钮数组
private JButton[] buttons;
// 按钮文本
private final String[] characters = { "7", "8", "9", "/", "4", "5", "6",
"*", "1", "2", "3", "-", "0", ".", "=", "+" };
// 是否为第一个输入的数字
private boolean isFirstDigit = true;
// 运算结果
private double resultNum = 0.0;
// 运算符
private String operator = "=";
public Calculator(String title) {
// 设置标题栏
super(title);
// 初始化各组件
init();
// 注册各组件监听器
registerListener();
// 显示窗体
setVisible(true);
}
/**
* 初始化各组件
*/
private void init() {
// 常用属性初始化
setSize(220, 200);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
/* 文本框对象初始化 */
result = new JTextField("0");
// 文本右对齐
result.setHorizontalAlignment(JTextField.RIGHT);
// 设置是否可编辑
result.setEditable(false);
/* 按钮初始化 */
buttons = new JButton[characters.length];
for (int i = 0; i buttons.length; i++) {
buttons[i] = new JButton(characters[i]);
buttons[i].setFocusable(false); // 不允许按钮定位焦点
}
/* 将文本框与按钮添加到窗体中 */
add(result, BorderLayout.NORTH);
JPanel pnl = new JPanel(new GridLayout(4, 4, 5, 5));
for (JButton jButton : buttons) {
pnl.add(jButton);
}
add(pnl);
this.getContentPane().setFocusable(true);
}
/**
* 注册监听器
*/
private void registerListener() {
for (JButton jButton : buttons) {
jButton.addActionListener(this);
}
// 注册键盘事件
this.getContentPane().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
String text = String.valueOf(e.getKeyChar());
if (Character.isDigit(text.charAt(0)) || ".".equals(text)) { // 数字或小数点
handleNumber(text);
} else if ("+-*/=".indexOf(text) != -1) { // 运算符
handleOperator(text);
} else if (e.getKeyCode() == 8) { // 退格键
String tmp = result.getText().trim();
if (tmp.length() == 1) {
result.setText("0");
isFirstDigit = true;
} else {
result.setText(tmp.substring(0, tmp.length() - 1));
}
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
String text = btn.getText().trim();
if (Character.isDigit(text.charAt(0)) || ".".equals(text)) { // 处理数字和小数点
handleNumber(text);
} else { // 处理运算符
handleOperator(text);
}
}
/**
* 处理数字和小数点
*
* @param text
*/
private void handleNumber(String text) {
if (isFirstDigit) { // 第一次输入
if (".".equals(text)) {
this.result.setText("0.");
} else {
this.result.setText(text);
}
} else if ("0".equals(text) "0".equals(this.result.getText())) {
isFirstDigit = true;
return;
} else if (".".equals(text) this.result.getText().indexOf(".") == -1) {
this.result.setText(this.result.getText() + ".");
} else if (!".".equals(text)) {
this.result.setText(this.result.getText() + text);
}
isFirstDigit = false;
}
/**
* 处理运算符
*
* @param text
*/
private void handleOperator(String text) {
switch (operator) { // 处理各项运算 适用于JDK1.7版本的
case "+":
resultNum += Double.parseDouble(this.result.getText());
break;
case "-":
resultNum -= Double.parseDouble(this.result.getText());
break;
case "*":
resultNum *= Double.parseDouble(this.result.getText());
break;
case "/":
resultNum /= Double.parseDouble(this.result.getText());
break;
case "=":
resultNum = Double.parseDouble(this.result.getText());
break;
}
// 将文本框的值修改为运算结果
this.result.setText(String.valueOf(resultNum));
// 将点击的运算符放入operator保存
operator = text;
// 下一个数字第一次点击
isFirstDigit = true;
}
public static void main(String[] args) {
new Calculator("My Calculator");
}
}
运行结果如下: