计算器(JAVA实现)

  1 package mycalculator;
  2 /*
  3  *
  4  * 3---3  会有异常
  5  *
  6  *
  7  *
  8  * */
  9 import java.awt.*;
 10 import java.awt.event.*;
 11 import javax.swing.*;
 12 import java.util.*;
 13
 14 public class Calculator extends JFrame implements ActionListener, KeyListener,
 15         MouseListener {
 16     final int WIDTH = 440, HEIGHT = 350;
 17     GridLayout gridLayout = new GridLayout(4, 4, 5, 5); // 勿忘初始化 不初始化不会报错,但面板是空的
 18     BorderLayout borderLayout = new BorderLayout();
 19     FlowLayout flowLayout = new FlowLayout();
 20     Container container;
 21     // Container cont;
 22     JPanel panel, buttonPanel;
 23     JButton[] buttons;
 24     String[] name;
 25     JTextField textField;
 26     boolean cleared = true;
 27
 28     public Calculator() {
 29         super("Calculator");
 30         container = getContentPane();
 31         // Cont = getContentPane();
 32         // Cont.setLayout(borderLayout);
 33         buttonPanel = new JPanel();
 34         panel = new JPanel();
 35         // container = new Container();
 36         // Cont.add(container, borderLayout.CENTER);
 37         // panel.setSize(380,380);
 38         buttonPanel.setLayout(gridLayout);
 39         textField = new JTextField(15);
 40         textField.setFont(textField.getFont().deriveFont(Font.BOLD,
 41                 (float) 32.0));
 42         textField.setEditable(false);
 43         textField.setHorizontalAlignment(JTextField.RIGHT);
 44         textField.setBackground(Color.GRAY);
 45         textField.setForeground(Color.WHITE);
 46         panel.add(textField);
 47         // textField.setSize(getBounds().width,getBounds().height/3);
 48         // textField.setFont(textField.getFont().deriveFont(99));
 49         /*
 50          * container.setLayout(borderLayout); container.add(textField,
 51          * borderLayout.NORTH); container.add(cont, borderLayout.CENTER);
 52          */
 53         container.setLayout(borderLayout);
 54         // container.add(textField);
 55         container.add(panel, borderLayout.NORTH);
 56         container.add(buttonPanel, borderLayout.CENTER);
 57         // container.setSize(getBounds().width,getBounds().height);
 58         // cont.setSize(getBounds().width,getBounds().height/3*2);
 59         buttons = new JButton[16];
 60         name = new String[] { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2",
 61                 "3", "-", "0", ".", "=", "+" };
 62         for (int index = 0; index <= 15; index++) {
 63             buttons[index] = new JButton(name[index]);
 64             buttons[index].addActionListener(this);
 65             buttons[index].setBackground(Color.GRAY);
 66             buttons[index].setForeground(Color.WHITE);
 67             buttons[index].addKeyListener(this);
 68             buttons[index].addMouseListener(this);
 69             buttons[index].setFont(buttons[index].getFont().deriveFont(
 70                     Font.BOLD, (float) 32.0));
 71             // buttons[index].setSize(200, 200);
 72             buttonPanel.add(buttons[index]);
 73         }
 74         this.addKeyListener(this);
 75         setSize(WIDTH, HEIGHT);
 76         Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包
 77         Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸
 78         int screenWidth = screenSize.width; // 获取屏幕的宽
 79         int screenHeight = screenSize.height; // 获取屏幕的高
 80         setLocation(screenWidth / 2 - WIDTH / 2, screenHeight / 2 - HEIGHT / 2);// 设置窗口居中显示
 81         // setLocation(600, 250);
 82         setVisible(true);
 83         setFocusable(true);
 84     }
 85
 86     String calculate(String str) {
 87         String result = "Wrong Expression";
 88         String temp = "";
 89         if (str.charAt(0) != ‘-‘
 90                 && !(str.charAt(0) <= ‘9‘ && str.charAt(0) >= ‘0‘)) {
 91             return result;
 92         }
 93         LinkedList<Double> list = new LinkedList<Double>();
 94         LinkedList<Character> optList = new LinkedList<Character>();
 95         Double doubleTemp;
 96         boolean isFormerOpt = true;
 97         for (int index = 0; index <= str.length() - 1; index++) {
 98             if (index == 0) {
 99                 isFormerOpt = true;
100             } else {
101                 if (str.charAt(index - 1) > ‘9‘ || str.charAt(index - 1) < ‘0‘) {
102                     isFormerOpt = true;
103                 } else {
104                     isFormerOpt = false;
105                 }
106             }
107             if (str.charAt(index) != ‘+‘ && str.charAt(index) != ‘*‘
108                     && str.charAt(index) != ‘/‘
109                     && (!(str.charAt(index) == ‘-‘ && isFormerOpt == false))) {
110                 temp += str.charAt(index);
111             } else {
112                 doubleTemp = new Double(temp);
113                 list.add(doubleTemp);
114                 temp = "";
115                 optList.add(str.charAt(index));
116             }
117         }
118         doubleTemp = new Double(temp);
119         list.add(doubleTemp);
120         temp = "";
121         /*
122          * for (int index = 0; index <= list.size() - 1; index++) {
123          * System.out.println(list.get(index)); } for (int index = 0; index <=
124          * optList.size() - 1; index++) {
125          * System.out.println(optList.get(index)); }
126          */
127         boolean isThereHigherOpt = true;
128         while (isThereHigherOpt == true) {
129             /*
130              * for (Iterator<Character> it = optList.iterator(); it.hasNext();)
131              * { if (it.next() == ‘*‘ || it.next() == ‘/‘) { isThereHigherOpt =
132              * true; int index = optList.indexOf(it.next());
133              *
134              * break; } }
135              */
136             isThereHigherOpt = false;
137             for (int index = 0; index <= optList.size() - 1; index++) {
138                 if (optList.get(index) == ‘*‘) {
139                     Double t = list.get(index) * list.get(index + 1);
140                     list.remove(index + 1);
141                     list.set(index, t);
142                     optList.remove(index);
143                     isThereHigherOpt = true;
144                     break;
145                 }
146                 if (optList.get(index) == ‘/‘) {
147                     Double t = list.get(index) / list.get(index + 1);
148                     list.remove(index + 1);
149                     list.set(index, t);
150                     optList.remove(index);
151                     isThereHigherOpt = true;
152                     break;
153                 }
154             }
155         }
156         while (optList.isEmpty() == false) {
157             for (int index = 0; index <= optList.size() - 1; index++) {
158                 if (optList.get(index) == ‘+‘) {
159                     Double t = list.get(index) + list.get(index + 1);
160                     list.remove(index + 1);
161                     list.set(index, t);
162                     optList.remove(index);
163                     break;
164                 }
165                 if (optList.get(index) == ‘-‘) {
166                     Double t = list.get(index) + 0.0 - list.get(index + 1);
167                     list.remove(index + 1);
168                     list.set(index, t);
169                     optList.remove(index);
170                     break;
171                 }
172             }
173         }
174         /*
175          * System.out.println("/////////////////////////////////"); for (int
176          * index = 0; index <= optList.size() - 1; index++) { //
177          * System.out.println(index); System.out.println(list.get(index));
178          * System.out.println(optList.get(index));
179          * System.out.println(list.get(index + 1)); }
180          */
181         if (list.size() == 1) {
182             result = list.get(0).toString();
183         }
184         return result;
185     }
186
187     void addText(char ch) {
188         if (cleared == true && ((ch <= ‘9‘ && ch >= ‘0‘))) {
189             textField.setText("");
190             cleared = false;
191         }
192         String str = textField.getText();
193         if (ch != ‘=‘) {
194             if (str.length() > 0) {
195                 if (str.charAt(str.length() - 1) <= ‘9‘
196                         && str.charAt(str.length() - 1) >= ‘0‘) {
197                     if (ch != ‘.‘) {
198                         textField.setText(str + ch);
199                     } else {
200                         boolean isTherePoint = false;
201                         int i = str.length() - 1;
202                         while (i >= 0) {
203                             if (str.charAt(i) == ‘*‘ || str.charAt(i) == ‘/‘
204                                     || str.charAt(i) == ‘+‘
205                                     || str.charAt(i) == ‘-‘) {
206                                 break;
207                             }
208                             if (str.charAt(i) == ‘.‘) {
209                                 isTherePoint = true;
210                                 break;
211                             }
212                             i--;
213                         }
214                         if (isTherePoint == false) {
215                             textField.setText(str + ch);
216                         }
217                     }
218                 } else {
219                     if ((ch <= ‘9‘ && ch >= ‘0‘) || ch == ‘-‘) {
220                         textField.setText(str + ch);
221                     }
222                 }
223             } else {
224                 if (ch == ‘-‘ || (ch <= ‘9‘ && ch >= ‘0‘))
225                     textField.setText(str + ch);
226             }
227             cleared = false;
228         } else {
229             if (cleared == true) {
230                 textField.setText("");
231             } else {
232                 str = textField.getText();
233                 //System.out.println(str);
234                 textField.setText("");
235                 if (str.length() > 0) {
236                     if (str.charAt(str.length() - 1) <= ‘9‘
237                             && str.charAt(str.length() - 1) >= ‘0‘) {
238                         textField.setText(calculate(str));
239                     } else {
240                         textField.setText("Wrong Expression");
241                     }
242                 }
243             }
244             cleared = true;
245         }
246     }
247
248     public void actionPerformed(ActionEvent event) {
249         Object source = event.getSource();
250         if (source.getClass() == JButton.class) {
251             JButton button = (JButton) source;
252             char ch = button.getText().charAt(0);
253             addText(ch);
254         }
255     }
256
257     public void keyPressed(KeyEvent e) {
258     }
259
260     public void keyReleased(KeyEvent e) {
261     }
262
263     public void keyTyped(KeyEvent e) {
264         char ch = e.getKeyChar();
265         if (ch == ‘ ‘) {
266             System.exit(EXIT_ON_CLOSE);
267         }
268         if (ch == KeyEvent.VK_ENTER) {
269             buttons[14].setBackground(Color.LIGHT_GRAY);
270             for (int i = 0; i <= name.length - 1; i++) {
271                 if (i != 14) {
272                     buttons[i].setBackground(Color.GRAY);
273                 }
274             }
275             addText(‘=‘);
276             return;
277         }
278         for (int index = 0; index <= name.length - 1; index++) {
279             if (ch == name[index].charAt(0)) {
280                 // System.out.println(ch);
281                 buttons[index].setBackground(Color.LIGHT_GRAY);
282                 for (int i = 0; i <= name.length - 1; i++) {
283                     if (i != index) {
284                         buttons[i].setBackground(Color.GRAY);
285                     }
286                 }
287                 addText(ch);
288                 break;
289             }
290         }
291     }
292
293     public void mouseClicked(MouseEvent event) {
294     }
295
296     public void mouseEntered(MouseEvent event) {
297         Object source = event.getSource();
298         if (source.getClass() == JButton.class) {
299             JButton button = (JButton) source;
300             // System.out.println("hey");
301             button.setBackground(Color.LIGHT_GRAY);
302         }
303     }
304
305     public void mousePressed(MouseEvent event) {
306     }
307
308     public void mouseReleased(MouseEvent event) {
309     }
310
311     public void mouseExited(MouseEvent event) {
312         Object source = event.getSource();
313         if (source.getClass() == JButton.class) {
314             JButton button = (JButton) source;
315             // System.out.println("hey");
316             button.setBackground(Color.GRAY);
317         }
318     }
319
320     public static void main(String[] args) {
321         Calculator c = new Calculator();
322         // c.addKeyListener(c);
323         c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
324     }
325 }

计算9/3-1*2+-1

的结果=0。

时间: 2024-11-12 18:36:46

计算器(JAVA实现)的相关文章

简单计算器 java实现hdu1237

简单计算器 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 15190    Accepted Submission(s): 5184 Problem Description 读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值. Input 测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,

Intent相关知识点

Intent的中文意思是“意图,目的”的意思,可以理解为不同组件之间通信的“媒介”或者“信使”. 目标组件一般要通过Intent来声明自己的条件,一般通过组件中的<intent-filter>元素来过滤. Intent在由以下几个部分组成:动作(action),数据(data),分类(Category),类型(Type),组件(Component),和扩展信息(Extra). Intent在寻找目标组件的时候有两种方法:第一,通过组件名称直接指定:第二,通过Intent Filter过滤指定

玩转Android---组件篇---Intent(意图)

Intent的中文意思是“意图,目的”的意思,可以理解为不同组件之间通信的“媒介”或者“信使”. 目标组件一般要通过Intent来声明自己的条件,一般通过组件中的<intent-filter>元素来过滤. Intent在由以下几个部分组成:动作(action),数据(data),分类(Category),类型(Type),组件(Component),和扩展信息(Extra). Intent在寻找目标组件的时候有两种方法:第一,通过组件名称直接指定:第二,通过Intent Filter过滤指定

JAVA编写的简单计算器

package com.hellojava.practice.test; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; impo

[Java.web]简单计算器

项目的  WebRoot 目录下的 calculator.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>计算结果</title> </head> <body> <jsp:us

Java计算器

代码 1 import javax.swing.*; 2 import java.awt.*; 3 import java.awt.event.*; 4 5 public class Calculator extends JFrame{ 6 private String[] labels = { 7 "%","√","x2","1/x", 8 "CE","C","←"

Java写的一个计算器模拟小程序

下个周六又要参加自考实践上机考试了,时间过的好快,天冷了人也变懒惰了,有时候什么也不想干,今晚刚好有时间就抽空把JAVA的试题拿出来再复习复习,看书比较困乏索性就敲敲代码吧,说实话我对JAVA不是很熟,如果不是因为考试要考,我也没时间接触它,毕竟做运维的,我更喜欢shell,PYTHON之类的.算了,还是把刚敲的代码放这里保存下,省的以后又找不到了.刚入门也就这样了. 题目: 编写一个计算器模拟程序.界面采用4行3列布局,界面设有3个文字标签(运算数1.运算数2.计算结果).3个文本框和3个加.

《java小应用程序(Applet)和java应用程序(Application)分别编写的简单计算器》

Application和Java Applet的区别.Java语言是一种半编译半解释的语言.Java的用户程序分为两类:Java Application和Java Applet.这两类程序在组成结构和执行机制上都有一定的差异,主要体现在以下几方面:(1)运行方式不同.Java Application是完整的程序,可以独立运行:Java Applet程序不能单独运行, 它必须嵌入到用HTML语言编写的Web页面中,通过与Java兼容的浏览器来控制执行.(2)运行工具不同.Java Applicat

Java简单计算器

import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.s

Java图形化界面设计——布局管理器之GridLayout(网格布局) 之计算器

代码如下: import java.awt.*; import javax.swing.*; public class GridFrame extends JFrame { // 定义字符串数组,为按钮的显示文本赋值 String str[] = { "MC", "MR", "MS", "M+", "←", "C", "%", "π", "