编写一个能四则运算的计算机程序,哪位大佬讲解一下?
实现一个具有四则运算的计算器,能够实现基本的加、减、乘、除等运算,有小数点、正负号、求倒数、退格和清零功能以及完善其它的辅助功能;界面简
洁适用。主要练习使用布局管理器设计一个计算器的界面,并练习使用事件监听
器处理数据的输入,并完成相关的计算。
package com.huawei.test; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import java.util.regex.*; import javax.swing.*; public class Cal extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 1L; JTextField jtf = new JTextField(); public Cal() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); add(jtf, BorderLayout.NORTH); jtf.setEditable(false); JPanel jp = new JPanel(); List<String> list = new ArrayList<String>(20); List<String> list2 = new ArrayList<String>(Arrays.asList("+", "C", "-", "退格", "*", "1/x", "+/-", ".", "/", "=")); for(int i = 1; i < 10; i++) { list.add(i+""); if(i % 3 == 0) { list.addAll(list2.subList(0, 2)); list2.remove(0); list2.remove(0); } } list.add("0"); list.addAll(list2); jp.setLayout(new GridLayout(4, 5)); for(String str : list) { JButton btn = new JButton(str); btn.addActionListener(this); jp.add(btn); } add(jp, BorderLayout.CENTER); pack(); setLocation(200, 400); setResizable(false); } static String preTxt = null; @Override public void actionPerformed(ActionEvent e) { String btnTxt = ((JButton)e.getSource()).getText(); if("C".equals(btnTxt)) { jtf.setText(""); } else if("1/x".equals(btnTxt)) { double num = 0; try { num = Double.parseDouble(jtf.getText()); } catch (Exception e2) { System.out.println(e2.getMessage()); } jtf.setText(1/num+""); } else if("退格".equals(btnTxt)) { String content = jtf.getText(); if(content.length()>0) { content = content.substring(0, content.length()-1); } jtf.setText(content); } else if("+/-".equals(btnTxt)) { String content = jtf.getText(); if(content.startsWith("-")) { content = content.substring(1, content.length()); } else { content = "-" + content; } jtf.setText(content); } else if("=".equals(btnTxt)) { String content = jtf.getText(); content = getByRegex(content); jtf.setText(content); } else if(!"=".equals(preTxt)){ jtf.setText(jtf.getText()+btnTxt); } else { jtf.setText(btnTxt); } preTxt = btnTxt; } private static String calc(String content, String regex) { String pattern = regex; Pattern r = (pattern); Matcher m = r.matcher(content); if (m.find( )) { int a = Integer.parseInt(m.group(1)); int b = Integer.parseInt(m.group(3)); int res=0; if("*".equals(m.group(2))) { res = a*b; }else if("/".equals(m.group(2))) { res = a/b; }else if("+".equals(m.group(2))) { res = a+b; }else if("-".equals(m.group(2))) { res = a-b; } return content.replace(m.group(), res+""); } return content; } private String getByRegex(String content) { for(String type : Arrays.asList("*", "/", "+", "-")) { content = calc(content, "(\\d+)(\\"+type+")(\\d+)"); String content2 = null; while(!content.equals(content2)) { content2 = content; content = calc(content, "(\\d+)(\\"+type+")(\\d+)"); } } return content; } public static void main(String[] args) { new Cal(); } }