java计算器输入异常,Java计算器代码出现异常,不知道为什么输入“+”等字符会出错误...

Java codepackage com.easteq.test;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

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.swing.JTextField;

import javax.swing.border.LineBorder;

public class ButtonPanel implements ActionListener {

public ButtonPanel() {

// txt.setSize(200,80);

cPanel1.add(txt, BorderLayout.NORTH);

for (int i = 0; i <= 15; i++) {

button[i] = new JButton(s[i]);

button[i].addActionListener(this);

cPanel2.add(button[i]);

}

// cPanel1.add(cPanel2, BorderLayout.SOUTH);

}

public void actionPerformed(ActionEvent e) {

ready = txt.getText();

String etxt = e.getActionCommand();

String newTxt = "";

if (etxt.equals(".")) {

newTxt = ready + etxt;

}

else if (etxt.equals("+") || etxt.equals("-") || etxt.equals("*") || etxt.equals("/")) {

flag = etxt;

newTxt = ready + etxt;

}

else if (etxt.equals("=")) {

if (flag != null && f2 != 0f) {

float result = Result();

f1 = result;

flag = null;

newTxt = String.valueOf(result);

}

}

else { // now, numbers

if (flag == null) {

f1 = Float.parseFloat(ready + etxt);

}

else {

f2 = Float.parseFloat(etxt);;

}

newTxt = ready + etxt;

}

txt.setText(newTxt);

}

public float Result() {

System.out.println("Getting result of flag:" + flag);

if (flag.equals("+"))

result = f1 + f2;

if (flag.equals("-"))

result = f1 - f2;

if (flag == "*")

result = f1 * f2;

if (flag == "/")

result = f1 / f2;

return result;

}

public JPanel getCPanel1() {

return cPanel1;

}

public JPanel getCPanel2() {

return cPanel2;

}

private JButton[] button = new JButton[16];

private String s[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "/", ".", "0", "=" };

private JPanel cPanel1 = new JPanel();

private JPanel cPanel2 = new JPanel(new GridLayout(4, 4));

private JTextField txt = new JTextField(10);

private String ready = "";

private float f1 = 0f, f2 = 0f;

private String flag = null;

private float result;

public static void main(String[] args) {

JFrame frame = new JFrame();

ButtonPanel pan = new ButtonPanel();

frame.getContentPane().add(pan.getCPanel1(), "Center");

frame.getContentPane().add(pan.getCPanel2(), "South");

frame.setSize(200, 200);

frame.setVisible(true);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值