您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要介绍“Java怎么实现图形界面计算器”,在日常操作中,相信很多人在Java怎么实现图形界面计算器问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Java怎么实现图形界面计算器”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
代码:
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Stack; public class Calculator extends JFrame implements ActionListener { private final String[] ButtonNames = {"(", ")", "←", "C", "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "0", "=", "/"}; private JTextField DisplayBox = new JTextField("0.0"); private JTextField Cache = new JTextField(""); private JButton[] Buttons = new JButton[ButtonNames.length]; public Calculator() { super(); setTitle("计算器"); init(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 400, 600); setResizable(false); //窗口不可调整大小 setVisible(true); } private void init() { //完成布局以及定义监听器 DisplayBox.setHorizontalAlignment(JTextField.RIGHT); //文本框右对齐 DisplayBox.setFont(new Font("DIN", Font.BOLD, 30)); //DIN:一种数字常用字体 Cache.setFont(new Font("DIN", Font.BOLD, 30)); GridBagLayout gridBagLayout = new GridBagLayout(); //采取网格包布局 GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.fill = GridBagConstraints.BOTH; //该方法是为了设置如果组件所在的区域比组件本身要大时的显示情况 gridBagConstraints.weightx = 1; //使组件的大小取得最大空间 gridBagConstraints.weighty = 1; setLayout(gridBagLayout); gridBagConstraints.gridx = 0; //缓存区起始位置为(0,0),横向占据4格,纵向1格 gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 4; gridBagConstraints.gridheight = 1; gridBagLayout.setConstraints(Cache, gridBagConstraints); this.add(Cache); gridBagConstraints.gridx = 0; //文本框起始位置为(0,0),横向占据4格,纵向2格 gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 4; gridBagConstraints.gridheight = 2; gridBagLayout.setConstraints(DisplayBox, gridBagConstraints); this.add(DisplayBox); gridBagConstraints.gridy = 3; //按钮起始位置为(0,3) gridBagConstraints.gridwidth = 1; //每个按钮占据1格 gridBagConstraints.gridheight = 1; for (int i = 0; i < ButtonNames.length; i++) { Buttons[i] = new JButton(ButtonNames[i]); } int n = 0; //记录每一行输出的按钮数,满4换行 for (int i = 0; i < Buttons.length; i++) { gridBagLayout.setConstraints(Buttons[i], gridBagConstraints); this.add(Buttons[i]); n++; if (n == 4) { gridBagConstraints.gridx = 0; gridBagConstraints.gridy++; n = 0; } else { gridBagConstraints.gridx++; } } for (int i = 0; i < Buttons.length; i++) { //事件监听器 Buttons[i].addActionListener(this); } } @Override public void actionPerformed(ActionEvent e) { //对事件的处理 String str; String value = e.getActionCommand(); //获取按钮的值 char v = value.charAt(0); switch (v) { case 'C': DisplayBox.setText("0.0"); break; case '←': DeleteOne(); break; case '=': String string = DisplayBox.getText(); Cache.setText(string + "="); if (isTrue(string)) { //若格式正确 str = retureResult(); DisplayBox.setText(str); } else { DisplayBox.setText("输入格式不合法"); } break; default: AddOne(value); break; } } private void DeleteOne() { //删除一个字符 String str; str = DisplayBox.getText(); if (str.length() == 1) { DisplayBox.setText("0.0"); } else if(!str.equals("0.0")) { str = str.substring(0, str.length() - 1); //去掉最后一个元素 DisplayBox.setText(str); } } private void AddOne(String value) { //增加一个字符 String str; str = DisplayBox.getText(); if (str.equals("0.0")) { //第一次输入 DisplayBox.setText(value); } else { str = str + value; DisplayBox.setText(str); } } private String retureResult() { //对输入的式子进行运算;基本方法:逆波兰法,中缀转后缀 String string = DisplayBox.getText(); String[] Midfix = breakDown(string); //中缀表达式的数组 String[] suffix = Conversion(Midfix); //得到后缀表达式 String result = Calculation(suffix); //计算后缀表达式结果 return result; } private String Calculation(String[] suffix) { Stack<String> stack = new Stack<>(); String symbols = "+-*/"; //转换为后缀表达式的式子只会有 +-*/ 符号不会有 () for (int i = 0; i < suffix.length; i++) { if (suffix[i] == null) { //suffix后面可能出现null 故对其筛选不进行下列的操作 continue; } if (symbols.indexOf(suffix[i]) >= 0) { //为符号时进行运算 double top1; double top2; double top; switch (suffix[i]) { case "+": top1 = Double.parseDouble(stack.pop()); //取栈顶将其转化为double top2 = Double.parseDouble(stack.pop()); top = top2 + top1; stack.push(String.valueOf(top)); //将top转化为String入栈 break; case "-": top1 = Double.parseDouble(stack.pop()); top2 = Double.parseDouble(stack.pop()); top = top2 - top1; stack.push(String.valueOf(top)); break; case "*": top1 = Double.parseDouble(stack.pop()); top2 = Double.parseDouble(stack.pop()); top = top2 * top1; stack.push(String.valueOf(top)); break; case "/": top1 = Double.parseDouble(stack.pop()); top2 = Double.parseDouble(stack.pop()); if (top1 == 0) { return "运算过程中除数出现0"; } top = top2 / top1; stack.push(String.valueOf(top)); break; } } else { //为数字直接入栈 stack.push(suffix[i]); } } String result = stack.pop(); return result; } private String[] breakDown(String string) { //将(2+3.14)+9分解成 ( 2 + 3.14 ) + 9便于后续计算 String[] split = string.split(""); String DigitString = "0123456789."; String afterSplit = ""; for (int i = 0; i < split.length; i++) { //将 2+3.14 变成 2,+,3.14 便于拆分 if (DigitString.indexOf(split[i]) >= 0) { afterSplit = afterSplit + split[i]; } else if(afterSplit.equals("") && DigitString.indexOf(split[i]) < 0) { //第一个为符号时只在后面加。 afterSplit = afterSplit + split[i] + ","; } else { //为 () 或 =-*/ 在其两侧加上 , afterSplit = afterSplit + "," + split[i] + ","; } } afterSplit = afterSplit.replace(",,", ","); //避免(2+3)+2产生……3,),,+,2 split = afterSplit.split(","); //产生的字符串数组中只会含+-*/()整数和小数 return split; } private String[] Conversion(String[] strings) { //中缀转后缀 String[] suffix = new String[strings.length]; //后缀表达式 int n = 0; //suffix的下标 Stack<String> stack = new Stack<>(); String first = "*/"; String symbols = "+-*/()"; for (int i = 0; i < strings.length; i++) { if(symbols.indexOf(strings[i]) >= 0) { //为符号时 if (stack.empty()) { stack.push(strings[i]); } else { //栈不为空 if(first.indexOf(strings[i]) >= 0 || strings[i].equals("(")) { //为 +/( 直接入栈 stack.push(strings[i]); } else if(strings[i].equals(")")) { String top = stack.peek(); while(!top.equals("(")) { top = stack.pop(); suffix[n] = top; n++; top = stack.peek(); } stack.pop(); // ( 出栈 } else { //符号为 +- if(first.indexOf(stack.peek()) < 0) { //当栈顶不为为 */ 直接入栈 stack.push(strings[i]); } else { while (!stack.empty() && first.indexOf(stack.peek()) >= 0) //栈顶运算符先于当前运算符时,出栈到栈顶运算符低于或栈为空为止 { String s = stack.pop(); suffix[n] = s; n++; } stack.push(strings[i]); //当前运算符入栈 } } } } else { //为数字直接成为后缀一部分 suffix[n] = strings[i]; n++; } } while (!stack.empty()) { //清除栈内剩余符号 String s = stack.pop(); suffix[n] = s; n++; } return suffix; } private boolean isTrue(String str) { if (!BracketMatching(str)) { //括号匹配 return false; } if (!OperatorIsTrue(str)) { //符号格式正确 return false; } return true; } private boolean OperatorIsTrue(String string) { //运算数数量 = 运算符号数+1 String[] split = breakDown(string); String symblos = "+-*/"; String bracket = "()"; int NumberOfDigits = 0; int NumberOfSymblos = 0; for (int i = 0; i < split.length; i++) { if(symblos.indexOf(split[i]) >= 0) { NumberOfSymblos++; } else if(bracket.indexOf(split[i]) < 0) { //不是括号 不是运算符一定为运算数 NumberOfDigits++; } } if (NumberOfDigits != NumberOfSymblos + 1) { return false; } return true; } private boolean BracketMatching(String string) { //判断括号是否匹配,否则报错 char[] split = string.toCharArray(); Stack<Character> stack = new Stack<>(); for (int i = 0; i < split.length; i++) { if (split[i] == '(') { stack.push(split[i]); } else if (!stack.empty() && split[i] == ')') { stack.pop(); } else if (stack.empty() && split[i] == ')') { return false; } } if (!stack.empty()) { return false; } return true; } public static void main(String[] args) { Calculator calculator = new Calculator(); } }
到此,关于“Java怎么实现图形界面计算器”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。