用Java设计一个简单的计算器。
设计一个简单的计算器,能够对两个数据进行“加、减、乘、除”运算。要求:合理应用布局设计,注重界面美观、友好,要求处理NumberFormatException异常。...
设计一个简单的计算器,能够对两个数据进行“加、减、乘、除”运算。要求:合理应用布局设计,注重界面美观、友好,要求处理NumberFormatException异常。
展开
8个回答
展开全部
无聊写了个,修复了下Bug:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Calculate extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton plus, reduce, multiply, divice, reset;
private JTextField one, two, result;
private boolean device_falg = false;
private final int width = 400, height = 300;
public Calculate() {
super("修改密码");
this.setLayout(null);
this.setSize(width, height);
init();
Layout();
}
public void init() {
plus = new JButton("加 ");
reduce = new JButton("减 ");
multiply = new JButton("乘 ");
divice = new JButton("除 ");
reset = new JButton("清空");
one = new JTextField();
two = new JTextField();
result = new JTextField();
}
public void Layout() {
this.add(new JLabel("第一个数")).setBounds(20, 10, 60, 80);
this.add(one).setBounds(100, 38, 100, 25);
this.add(new JLabel("第二个数")).setBounds(20, 40, 60, 80);
this.add(two).setBounds(100, 70, 100, 25);
this.add(new JLabel("结果")).setBounds(20, 85, 60, 80);
this.add(result).setBounds(100, 110, 100, 25);
this.add(plus).setBounds(70, 170, 80, 25);
this.add(reduce).setBounds(200, 170, 80, 25);
this.add(multiply).setBounds(70, 200, 80, 25);
this.add(divice).setBounds(200, 200, 80, 25);
this.add(reset).setBounds(300, 220, 80, 25);
plus.addActionListener(this);
reduce.addActionListener(this);
multiply.addActionListener(this);
divice.addActionListener(this);
reset.addActionListener(this);
this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public boolean Format() {
boolean FLAG = false;
boolean flag = false;
String one = this.one.getText().toString().trim();
String two = this.two.getText().toString().trim();
if (one == null || one.equals("") || two == null || two.equals("")) {
JOptionPane.showMessageDialog(getParent(), "请输入完整信息!");
FLAG = false;
flag = true;
}
boolean boll_1 = one.matches("[\\d]{1,100}");
boolean boll_2 = two.matches("[\\d]{1,100}");
boolean boll_3 = one.matches("[\\d]{1,100}+[.]+[\\d]{1,100}");
boolean boll_4 = two.matches("[\\d]{1,100}+[.]+[\\d]{1,100}");
if (flag) {
return false;
}
if ((boll_1 && boll_2) || (boll_3 && boll_4) || (boll_1 && boll_4)
|| (boll_3 && boll_2)) {
FLAG = true;
} else {
JOptionPane.showMessageDialog(getParent(), "请输入数字!");
FLAG = false;
}
if (FLAG && device_falg) {
if (Double.parseDouble(two) == 0) {
JOptionPane.showMessageDialog(getParent(), "被除数不能为0!");
FLAG = false;
device_falg=false;
}
}
return FLAG;
}
public double Plus(double one, double two) {
return one + two;
}
public double Multiply(double one, double two) {
return one * two;
}
public double Divice(double one, double two) {
return one / two;
}
public double Reduce(double one, double two) {
return one - two;
}
public void Clear() {
one.setText("");
two.setText("");
result.setText("");
}
@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == reset) {
Clear();
return;
}
if (o == divice) {
device_falg = true;
}
if (!Format()) {
return;
}
double one = Double.parseDouble(this.one.getText());
double two = Double.parseDouble(this.two.getText());
double result = 0;
if (o == plus) {
result = Plus(one, two);
} else if (o == reduce) {
result = Reduce(one, two);
} else if (o == multiply) {
result = Multiply(one, two);
} else if (o == divice) {
result = Divice(one, two);
}
this.result.setText("" + result);
}
public static void main(String[] args) {
new Calculate();
}
}
追问
谢谢各位
展开全部
比一楼的简单
package com.isoftstone.baidu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CalcDemo extends JFrame {
private static final long serialVersionUID = 111111L;
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
private JLabel label3 = new JLabel();
private JTextField field1 = new JTextField();
private JTextField field2 = new JTextField();
private JTextField field3 = new JTextField();
private JButton button1 = new JButton();
private JButton button2 = new JButton();
private JButton button3 = new JButton();
private JButton button4 = new JButton();
public static void main(String[] args) {
new CalcDemo();
}
public CalcDemo() {
super("简易计算器");
try {
init();
} catch (Exception e) {
e.printStackTrace();
}
}
private void init() {
this.setSize(300, 300);
label1.setText("第一个数:");
label2.setText("第二个数:");
label3.setText("结果:");
button1.setText("加法");
button2.setText("减法");
button3.setText("乘法");
button4.setText("除法");
label1.setBounds(10, 10, 100, 22);
label2.setBounds(10, 35, 100, 22);
label3.setBounds(10, 60, 100, 22);
field1.setBounds(110, 10, 100, 22);
field2.setBounds(110, 35, 100, 22);
field3.setBounds(110, 60, 100, 22);
button1.setBounds(10, 85, 100, 22);
button2.setBounds(110, 85, 100, 22);
button3.setBounds(110, 110, 100, 22);
button4.setBounds(10, 110, 100, 22);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculate(1);
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculate(2);
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculate(3);
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculate(4);
}
});
JPanel panel = (JPanel) this.getContentPane();
panel.setLayout(null);
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(field1);
panel.add(field2);
panel.add(field3);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private void calculate(int operators) {
try {
double num1 = Double.parseDouble(field1.getText());
double num2 = Double.parseDouble(field2.getText());
switch (operators) {
case 1:
field3.setText((num1 + num2) + "");
break;
case 2:
field3.setText((num1 - num2) + "");
break;
case 3:
field3.setText((num1 * num2) + "");
break;
case 4:
field3.setText((num1 / num2) + "");
break;
default:
break;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "请输入正确的数值!!!", "警告", 1);
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.JOptionPane;
public class Calculator extends Applet implements ActionListener{
Button backButton=new Button("退格");
Button clearButton=new Button("清除");
Panel p1 = new Panel(new FlowLayout());
Panel p2 = new Panel(new GridLayout(2,1));
Panel p3 = new Panel(new GridLayout(4,5,5,5));
TextField t=new TextField("0");
float num1=0;
char ch='#';boolean can=false;
public void init(){
t.setFont(new Font("宋体",Font.BOLD,25));
backButton.setFont(new Font("黑体",Font.BOLD,15));
backButton.setForeground(Color.red);
clearButton.setFont(new Font("黑体",Font.BOLD,15));
clearButton.setForeground(Color.red);
p1.add(backButton);
p1.add(clearButton);
backButton.addActionListener(this);
clearButton.addActionListener(this);
p2.add(t);
p2.add(p1);
p2.setBackground(Color.black);
p3.setBackground(Color.black);
this.setLayout(new BorderLayout());
this.add(p2,"North");
this.add(p3,"Center");
String buttonStr = "789/A456*B123-C0.D+=";
for (int i = 0; i < buttonStr.length(); i++)
this.addButton(p3,buttonStr.substring(i, i + 1));
}
private void addButton(Container c, String s)
{Button b = new Button(s);
if (s.equals("A"))
b.setLabel("sqrt");
else if (s.equals("B"))
b.setLabel("1/x");
else if (s.equals("C"))
b.setLabel("%");
else if (s.equals("D"))
b.setLabel("+/-");
b.setForeground(Color.blue);
b.setFont(new Font("黑体",Font.BOLD,15));
c.add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String act=e.getActionCommand();
if(e.getSource()==backButton){
if(t.getText().length()>1)t.setText(t.getText().substring(0, t.getText().length()-1));
else t.setText("0");
return;}
if(e.getSource()==clearButton){t.setText("0");ch='#';return;}
if(act.equals("+/-")){
if(t.getText().charAt(0)!='-')t.setText("-"+t.getText());
else t.setText(t.getText().substring(1));return;
}
if(act.equals(".")){t.setText(t.getText()+act);return;}
if(act!="1/x"&&act.charAt(0)>='0'&&act.charAt(0)<='9'){
if(can){t.setText(act);can=false;}
else{try{if(Float.parseFloat(t.getText())==0)
{if(t.getText().equals("0."))t.setText(t.getText()+act);
else t.setText(act);
return;
}
else {t.setText(t.getText()+act);return;}
}catch(NumberFormatException e1){
JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
}
if(act.equals("+")||act.equals("-")||act.equals("*")||act.equals("/")||act.equals("%")){
if(ch!='#'){try{num1=cacu(num1,ch,Float.parseFloat(t.getText()));
t.setText(String.valueOf(num1));ch=act.charAt(0);can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
else{try{num1=Float.parseFloat(t.getText());
ch=act.charAt(0);can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
}
if(act.equals("sqrt")){try{float num=(float)Math.sqrt(Float.parseFloat(t.getText()));
t.setText(String.valueOf(num));can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
if(act.equals("1/x")){try{float num=1/Float.parseFloat(t.getText());
t.setText(String.valueOf(num));can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
catch(ArithmeticException e1){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
if(act.equals("=")){can=true;
try{if(ch=='#')return;
float num=Float.parseFloat(t.getText());
num1=cacu(num1,ch,num);
t.setText(String.valueOf(num1));
ch='#';return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
}
public float cacu(float a,char c,float b){
float sum;
switch(c){
case '+':sum=a+b;break;
case '-':sum=a-b;break;
case '*':sum=a*b;break;
case '/':if(b==0){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return 0;}sum=a/b;break;
case '%':if(b==0){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return 0;}sum=a%b;break;
default:return 0;
}
return sum;
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
说实在的,你写的这个计算器不怎么样。特别是布局。
我给你一个很简单的吧。你自己学习一下。。
import java.awt.*;
import java.awt.event.*;
/**
*
* @author zzj
*
*/
public class Jisuanqi extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
TextField txt;
private Button[] b = new Button[17];
private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "清空", "0", "=", "/", "关闭" };
static double a;
static String s, str;//定义变量 创建对像
public static void main(String args[]) {
(new Jisuanqi()).frame();
}
public void frame() {
Frame fm = new Frame("简单计算器");
for (int i = 0; i <= 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i <= 15; i++) {
p2.add(b[i]);
} //创建按钮 并添加到P2
b[16].setBackground(Color.yellow);
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i <= 16; i++) {
b[i].addActionListener(new buttonlistener());//添加监听器
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "North");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);//都是些窗中设置 添加相关组件和监听器
}
public void windowClosing(WindowEvent e) {
System.exit(0);//退出系统
}
class buttonlistener implements ActionListener {//编写监听器事件 通过按键得出给果
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
jisuan();
str = String.valueOf(a);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";
} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());
if (btn.getLabel() == "清空")
txt.setText("");
}
}
public void jisuan() {//编写具体计算方法
if (s == "+")
a += Double.parseDouble(txt.getText());
else if (s == "-")
a -= Double.parseDouble(txt.getText());
else if (s == "*")
a *= Double.parseDouble(txt.getText());
else if (s == "/")
a /= Double.parseDouble(txt.getText());
else
a = Double.parseDouble(txt.getText());
}
}
}
class close implements ActionListener {//退出
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
我给你一个很简单的吧。你自己学习一下。。
import java.awt.*;
import java.awt.event.*;
/**
*
* @author zzj
*
*/
public class Jisuanqi extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
TextField txt;
private Button[] b = new Button[17];
private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "清空", "0", "=", "/", "关闭" };
static double a;
static String s, str;//定义变量 创建对像
public static void main(String args[]) {
(new Jisuanqi()).frame();
}
public void frame() {
Frame fm = new Frame("简单计算器");
for (int i = 0; i <= 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i <= 15; i++) {
p2.add(b[i]);
} //创建按钮 并添加到P2
b[16].setBackground(Color.yellow);
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i <= 16; i++) {
b[i].addActionListener(new buttonlistener());//添加监听器
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "North");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);//都是些窗中设置 添加相关组件和监听器
}
public void windowClosing(WindowEvent e) {
System.exit(0);//退出系统
}
class buttonlistener implements ActionListener {//编写监听器事件 通过按键得出给果
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
jisuan();
str = String.valueOf(a);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";
} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());
if (btn.getLabel() == "清空")
txt.setText("");
}
}
public void jisuan() {//编写具体计算方法
if (s == "+")
a += Double.parseDouble(txt.getText());
else if (s == "-")
a -= Double.parseDouble(txt.getText());
else if (s == "*")
a *= Double.parseDouble(txt.getText());
else if (s == "/")
a /= Double.parseDouble(txt.getText());
else
a = Double.parseDouble(txt.getText());
}
}
}
class close implements ActionListener {//退出
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
- -|||……虽然我也有计算器的代码,不过我还是给你指正下你的问题出在哪里吧。很无语……
public void actionPerformed(ActionEvent e){
Button0.addActionListener(this);
if(e.getActionCommand().equals("Button1"))
Text1.setText(e.getActionCommand());
}
你应该把这里面的Button0.addActionListener(this);添加到Calculator类函数中.因为你是在Calculator类中触发了按钮事件,然后在actionPerformed(ActionEvent e)函数中处理它。你把它放到actionPerformed(ActionEvent e)函数中,又怎么能触发事件呢……
你修改看看吧,这样应该就可以用了
public void actionPerformed(ActionEvent e){
Button0.addActionListener(this);
if(e.getActionCommand().equals("Button1"))
Text1.setText(e.getActionCommand());
}
你应该把这里面的Button0.addActionListener(this);添加到Calculator类函数中.因为你是在Calculator类中触发了按钮事件,然后在actionPerformed(ActionEvent e)函数中处理它。你把它放到actionPerformed(ActionEvent e)函数中,又怎么能触发事件呢……
你修改看看吧,这样应该就可以用了
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询