求助:用java编一个简单的计算器

来源:百度知道 编辑:UC知道 时间:2024/05/16 10:06:46
不用JOption和数组;

要求如下:
Write a program Calculator.java to implement a simple calculator of basic operations (addition, subtraction, multiplication and division) on integers.

The user may enter a string comprising an operand, a binary operator, and a second operand, with any number of space characters between them. There may be leading spaces and trailing spaces in the input.

If an invalid input is encountered, a message "Error in expression" is displayed and the calculation is skipped. Otherwise, the respective operation is carried out, and the result displayed. The user then enters another string. To end the calculation, the user enters 'q' (without any leading or trailing spaces).

The operand is an integer. Examples of valid operands are 23, 0, -123, but not 23.5 (not an integer), 51.0 (not an integer), +123 (unary plus not accepted). You may assume that the operands and the result are within the range of value of the

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JFrame {

private Container container;
private GridBagLayout layout;
private GridBagConstraints constraints;
private JTextField displayField;//计算结果显示区
private String lastCommand;//保存+,-,*,/,=命令
private double result;//保存计算结果
private boolean start;//判断是否为数字的开始

public Calculator() {

super("Calculator");
container=getContentPane();
layout=new GridBagLayout();
container.setLayout(layout);
constraints=new GridBagConstraints();
start=true;
result=0;
lastCommand = "=";
displayField=new JTextField(20);
displayField.setHorizontalAlignment(JTextField.RIGHT);
constraints.gridx=0;
constraints.gridy=0;
constraints.gridwidth=4;
constraints.gridheight=1;
constraints.fill=GridBagConstraints.BOTH;
cons