本文目录一览:
JAVA 编写计算器 要代码最简单的
学java的时候自己编的,很简单,能够连续输入计算式后进行计算
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**简易计算器,能够进行简单的计算
*
* @see 2008.12.9
*/
public class CalculatorA
implements ActionListener{
private JFrame frame;
private JTextField field;
private JButton[] allButtons;
private JButton clearButton;
// private JButton backButton;
String result="";//保存结果
StringBuilder sb = new StringBuilder();//保存要进行的计算式
int x = 0; //用来判断上一次的事件类型
String str = "123+456-789*0.=/";
ArrayListString arrayList = new ArrayListString();//保存计算式,通过方法进行运算
public CalculatorA(){
frame = new JFrame("我的计算器v1.1");
frame.setLocation(300,300);
field = new JTextField(25);
allButtons = new JButton[16];
for(int i=0;iallButtons.length;i++){
allButtons[i]= new JButton(str.substring(i,i+1));
}
clearButton = new JButton("CLEAR");
// backButton = new JButton("——");
init();
setFondAndColor();
addEventHander();
}
public void init(){
frame.setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(field);
for(int i=0;iallButtons.length;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
//southPanel.add(backButton);
frame.add(northPanel,BorderLayout.NORTH);
frame.add(centerPanel,BorderLayout.CENTER);
frame.add(southPanel,BorderLayout.SOUTH);
}
//设置输入字体
public void setFondAndColor(){
field.setFont(new Font("宋体",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
field.setForeground(Color.RED);
//设置字体从右起始
field.setHorizontalAlignment(JTextField.RIGHT);
}
public void showMi(){
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void addEventHander(){
for(int i=0;iallButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
// backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得当前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //当x为0时表示还没有进行输入
result=str;
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 1){
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 2){
sb.delete(0,sb.length());
result = result+str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 3){
result = str;
sb.delete(0,sb.length());
arrayList.clear();
field.setText(str);
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
result = str;
sb.append(str);
field.setText(str);
x = 1;
}
else{
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
}
else if("+*-/".indexOf(str)!=-1){
if(x == 0){
field.setText("");
x = 2;
}
else if(x == 1){
result = result + str;
arrayList.add(sb.toString());
arrayList.add(str);
sb.append(str);
field.setText(result);
x = 2;
}
else if(x == 2){
x = 2;
}
else if(x == 3){
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 2;
}
else{
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
}
else if("=".equals(str)){
if(x == 0){
field.setText("0");
arrayList.clear();
result = "0";
x = 3;
}
else if(x == 1){
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
else if(x == 2){
field.setText("数据格式错误.....");
arrayList.clear();
x = 0;
}
else if(x == 3){
field.setText(result);
x = 3;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 3;
}
else {
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
}
else if("CLEAR".equals(str)){
arrayList.clear();
field.setText("0");
arrayList.add("0");
x = 4;
}
else{
if(result.length()1){
result = result.substring(0,result.length()-1);
if(sb.length()0){
sb.delete(sb.length()-1,sb.length());
}
else {
sb.delete(0,1);
}
field.setText(result);
x = 5;
}
else{
result = "";
sb.delete(0,sb.length());
arrayList.clear();
field.setText("0");
x = 0;
}
}
}
public static ArrayListString getResult(ArrayListString list){
String res = null;
String[] s = {"/","*","-","+"};
int i=0;
if(list.size()1){
for(;is.length;){
if(s[i].equals("/")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j+1)));
//本地的数据格式
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("*")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("-")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getNumberInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else {
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))+Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
}
}
return list;
}
//对数字字符串进行排除不必要符号
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;kc.length;k++){
c[k] = res.charAt(k);
}
for(int k=0;kc.length;k++){
if((c[k]= '0' c[k]= '9')|| c[k] == '.'){
s_temp += c[k];
}
}
return s_temp;
}
public static void main(String[] args){
new CalculatorA().showMi();
}
}
怎么用JAVA编程编写一个计算器?
打开IED:打开自己java编程的软件,采用的是eclipse软件。
建立java工程。
编写类。
编写类的详细步骤
1.类的基本结构:
由于这里用到了界面,所以要进行窗口界面的编程,按钮事件的处理,和计算处理界面;
package MyCaculator;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyCaculator extends JFrame {
private int add=1,sub=2,mul=3,div=4;
private int op=0;
boolean ifOp;
private String output="0";
private Button[] jba=new Button[]{new Button("7"),new Button("8"),
new Button("9"),new Button("+"),
new Button("4"),new Button("5"),new Button("6"),new Button("-"),
new Button("1"),new Button("2"),new Button("3"),new Button("*"),
new Button("0"),new Button("."),new Button("="),new Button("/")};
private JPanel jpt=new JPanel();
private JPanel jpb=new JPanel();
private JTextField jtf=new JTextField("");
private MyCaculator(){
}
private void operate(String x){
}
public String add(String x){
return output;
}
public String subtract(String x){
return output;
}
public String multiply(String x){
return output;
}
public String divide(String x){
return output;
}
public String Equals(String x){
return output;
}
public void opClean(){
}
class setOperate_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
}
}
class setLabel_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
}
}
public static void main(String[] args) {
}
}
2.建立构造方法:
所谓构造方法就是,对自己的主类进行初始化,代码如下:
private MyCaculator(){
jpt.setLayout(new BorderLayout());
jpt.add(jtf);
this.add(jpt,BorderLayout.NORTH);
jpb.setLayout(new GridLayout(4,4));
for(int i=0;ijba.length;i++){
jpb.add(jba[i]);
if(i==3||i==7||i==11||i==15||i==14)
jba[i].addActionListener(new setOperate_Act());
else
jba[i].addActionListener(new setLabel_Act());
}
this.add(jpb,BorderLayout.CENTER);
this.setSize(250, 200);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
3.建立数据计算方法
这里的数据计算方法有6个,一个是主方法其他几个是加减乘除的处理方法,代码如下:
private void operate(String x){
double x1=Double.valueOf(x);
double y=Double.valueOf(output);
switch(op){
case 0:output=x;break;
case 1:output=String.valueOf(y+x1);break;
case 2:output =String.valueOf(y-x1);break;
case 3:output =String.valueOf(y*x1);break;
case 4:
if(x1!=0) output=String.valueOf(y/x1);
else output="不能为0";
break;
}
}
public String add(String x){
operate(x);
op=add;
return output;
}
public String subtract(String x){
operate(x);
op=sub;
return output;
}
public String multiply(String x){
operate(x);
op=mul;
return output;
}
public String divide(String x){
operate(x);
op=div;
return output;
}
public String Equals(String x){
operate(x);
op=0;
return output;
}
public void opClean(){
op=0;
output ="0";
}
4.事件处理方法
这里的时间处理方法,没有建立一个整体的方法,二是在为了便于处理的方法,将按钮事件分成两个部分,并采用两个子类来实现,这两个类时内部类要写在主类内部的,代码如下:
class setOperate_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jba[3]){
jtf.setText(add(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[7]){
jtf.setText(subtract(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[11]){
jtf.setText(multiply(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[15]){
jtf.setText(divide(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[14]){
jtf.setText(Equals(jtf.getText()));
ifOp=true;
}
}
}
class setLabel_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
Button tempb=(Button)e.getSource();
if(ifOp){
jtf.setText(tempb.getLabel());
ifOp=false;
}else {
jtf.setText(jtf.getText()+tempb.getLabel());
}
}
}
5.建立main方法:
要想实现我们的代码,我们需在main方法中,实例化我们的对象。
public static void main(String[] args) {
new MyCaculator();
}
编写计算器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.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Jisuanqi extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Result result = new Result(); // 定义text的面板
Number_Key number_key = new Number_Key(); // 定义按钮面板
// 当点击按钮+、-、*、/时,com = true
boolean com = false;
// 当i=0时说明是我们第一次输入,字符串text不会累加
int i = 0;
// 存放text的内容
String text = "";
// 存放点击按钮+、-、*、/之前的数值
double defbutton = 0;
// +、-、*、/的代号分别为1,2,3,4
int symbol = 0;
// 构造函数
Jisuanqi() {
super("WangJiao"); // 设定标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设定关闭窗体时退出程序
JPanel pane = new JPanel(); // 定义主面板
pane.setLayout(new BorderLayout());
setBounds(380, 220, 30, 80); // 前两个参数是在屏幕上显示的坐标,后两个是大小
// 替换图标
ImageIcon icon = new ImageIcon("F:1.GIF");
// Jisuanqi.class.getResource("APPLE.GIF")
// );
setIconImage(icon.getImage());
pane.add(result, BorderLayout.NORTH);
pane.add(number_key, BorderLayout.CENTER);
pane.add(number_key.equal, BorderLayout.SOUTH);
number_key.one.addActionListener(this); // 对1按钮添加监听事件
number_key.two.addActionListener(this); // 对2按钮添加监听事件
number_key.three.addActionListener(this); // 对3按钮添加监听事件
number_key.four.addActionListener(this); // 对4按钮添加监听事件
number_key.five.addActionListener(this); // 对5按钮添加监听事件
number_key.six.addActionListener(this); // 对6按钮添加监听事件
number_key.seven.addActionListener(this); // 对7按钮添加监听事件
number_key.eight.addActionListener(this); // 对8按钮添加监听事件
number_key.nine.addActionListener(this); // 对9按钮添加监听事件
number_key.zero.addActionListener(this); // 对0按钮添加监听事件
number_key.ce.addActionListener(this); // 对置零按钮添加监听事件
number_key.plus.addActionListener(this); // 对+按钮添加监听事件
number_key.equal.addActionListener(this); // 对=按钮添加监听事件
number_key.sub.addActionListener(this); // 对-按钮添加监听事件
number_key.mul.addActionListener(this); // 对*按钮添加监听事件
number_key.div.addActionListener(this); // 对/按钮添加监听事件
number_key.point.addActionListener(this); // 对.按钮添加监听事件
setContentPane(pane);
pack(); // 初始化窗体大小为正好盛放所有按钮
}
// 各个按钮触发的事件
public void actionPerformed(ActionEvent e) {
/*
* 如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么com=true 如果没有com=
* false;或者是否点击数字键,如果是i = 1,如果没有 i = 0;
*/
if (e.getSource() == number_key.one) {
if (com || i == 0) {
result.text.setText("1");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "1");
}
} else if (e.getSource() == number_key.two) {
if (com || i == 0) {
result.text.setText("2");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "2");
}
} else if (e.getSource() == number_key.three) {
if (com || i == 0) {
result.text.setText("3");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "3");
}
} else if (e.getSource() == number_key.four) {
if (com || i == 0) {
result.text.setText("4");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "4");
}
} else if (e.getSource() == number_key.five) {
if (com || i == 0) {
result.text.setText("5");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "5");
}
} else if (e.getSource() == number_key.six) {
if (com || i == 0) {
result.text.setText("6");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "6");
}
} else if (e.getSource() == number_key.seven) {
if (com || i == 0) {
result.text.setText("7");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "7");
}
} else if (e.getSource() == number_key.eight) {
if (com || i == 0) {
result.text.setText("8");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "8");
}
} else if (e.getSource() == number_key.nine) {
if (com || i == 0) {
result.text.setText("9");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "9");
}
}
/*
* 对于0这个按钮有一定的说法,在我的程序里不会出现如00000这样的情况,我加了判断条件就是
* 如果text中的数值=0就要判断在这个数值中是否有.存在?如果有那么就在原来数值基础之上添 加0;否则保持原来的数值不变
*/
else if (e.getSource() == number_key.zero) { // result.text.getText()是得到text里内容的意思
if (com || i == 0) {
result.text.setText("0");
com = false;
i = 1;
} else {
text = result.text.getText();
if (Float.parseFloat(text) 0 || Float.parseFloat(text) 0) { // Float.parseFloat(text)就是类型转换了,下面都是一样
result.text.setText(text + "0");
} else {
if (text.trim().indexOf(".") == -1) {
result.text.setText(text);
} else {
result.text.setText(text + "0");
}
}
}
} else if (e.getSource() == number_key.ce) {
result.text.setText("0");
i = 0;
com = true;
// text = "";
defbutton = 0;
}
/*
* 本程序不会让一个数值中出现2个以上的小数点.具体做法是:判断是否已经存在.存在就不添加, 不存在就添加.
*/
else if (e.getSource() == number_key.point) {
if (com || i == 0) {
result.text.setText("0.");
com = false;
i = 1;
} else {
text = result.text.getText();
if (text.trim().indexOf(".") == -1) {
result.text.setText(text + ".");
} else {
result.text.setText(text);
}
}
} // 获得点击+之前的数值
else if (e.getSource() == number_key.plus) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 1;
} // 获得点击-之前的数值
else if (e.getSource() == number_key.sub) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 2;
} // 获得点击*之前的数值
else if (e.getSource() == number_key.mul) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol = 3;
} // 获得点击/之前的数值
else if (e.getSource() == number_key.div) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 4;
} else if (e.getSource() == number_key.equal) {
switch (symbol) {
case 1: { // 计算加法
double ad = defbutton
+ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 2: { // 计算减法
double ad = defbutton
- Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i = 0;
text = "";
break;
}
case 3: { // 计算乘法
double ad = defbutton
* Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 4: { // 计算除法
double ad = defbutton
/ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
}
System.out.println(com);
}
System.out.println(result.text.getText());
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Jisuanqi loveyou = new Jisuanqi();
loveyou.show();
}
}
// 计算器数字按钮定义面板
class Number_Key extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton zero = new JButton("0"); // 数字键0
JButton one = new JButton("1"); // 数字键1
JButton two = new JButton("2"); // 数字键2
JButton three = new JButton("3"); // 数字键3
JButton four = new JButton("4"); // 数字键4
JButton five = new JButton("5"); // 数字键5
JButton six = new JButton("6"); // 数字键6
JButton seven = new JButton("7"); // 数字键7
JButton eight = new JButton("8"); // 数字键8
JButton nine = new JButton("9"); // 数字键9
JButton plus = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div = new JButton("/");
JButton equal = new JButton("=");
JButton ce = new JButton("清零"); // 置零键
JButton point = new JButton(".");
Number_Key() {
setLayout(new GridLayout(4, 4, 1, 1)); // 定义布局管理器为网格布局
setBackground(Color.blue); // 设置背景颜色
// 添加按钮
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
add(plus);
add(sub);
add(mul);
add(div);
add(point);
add(equal);
add(ce);
}
}
// 计算器显示结果的窗体
class Result extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// text先是输入和结果
JTextField text = new JTextField("0");
@SuppressWarnings("deprecation")
Result() { // 讲输入的数字或得到的结果在text的右边显示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false); // 文本框不能编辑
setLayout(new BorderLayout()); // 设定布局管理器边框布局
add(text, BorderLayout.CENTER); // text放置在窗体的中间
}
}