×

java编写简易计算器初学者 java

java编写简易计算器初学者(怎么用java编写一个简单的计算器)

admin admin 发表于2022-09-05 11:08:47 浏览114 评论0

抢沙发发表评论

本文目录

怎么用java编写一个简单的计算器


/*

 * @(#)JCalculator.java 1.00 06/17/2015

 */

 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

 

/**

 * A simple calculator program.

 * 《p》I saw this program in a QQ group, and help a friend correct it.《/p》

 *

 * @author Singyuen Yip

 * @version 1.00 12/29/2009

 * @see JFrame

 * @see ActionListener

 */

public class JCalculator extends JFrame implements ActionListener {

    /**

     * Serial Version UID

     */

    private static final long serialVersionUID = -169068472193786457L;

    /**

     * This class help close the Window.

     * @author Singyuen Yip

     *

     */

    private class WindowCloser extends WindowAdapter {

       public void windowClosing(WindowEvent we) {

           System.exit(0);

       }

    }

 

    int i;

    // Strings for Digit & Operator buttons.

    private final String str = { “7“, “8“, “9“, “/“, “4“, “5“, “6“, “*“,“1“,

           “2“, “3“, “-“, “.“, “0“, “=“, “+“ };

    // Build buttons.

    JButton buttons = new JButton[str.length];

    // For cancel or reset.

    JButton reset = new JButton(“CE“);

    // Build the text field to show the result.

    JTextField display = new JTextField(“0“);

   

    /**

     * Constructor without parameters.

     */

    public JCalculator() {

       super(“Calculator“);

       // Add a panel.

       JPanel panel1 = new JPanel(new GridLayout(4, 4));

       // panel1.setLayout(new GridLayout(4,4));

       for (i = 0; i 《 str.length; i++) {

           buttons[i] = new JButton(str[i]);

           panel1.add(buttons[i]);

       }

       JPanel panel2 = new JPanel(new BorderLayout());

       // panel2.setLayout(new BorderLayout());

       panel2.add(“Center“, display);

       panel2.add(“East“, reset);

       // JPanel panel3 = new Panel();

       getContentPane().setLayout(new BorderLayout());

       getContentPane().add(“North“, panel2);

       getContentPane().add(“Center“, panel1);

       // Add action listener for each digit & operator button.

       for (i = 0; i 《 str.length; i++)

           buttons[i].addActionListener(this);

       // Add listener for “reset“ button.

       reset.addActionListener(this);

       // Add listener for “display“ button.

       display.addActionListener(this);

       // The “close“ button “X“.

       addWindowListener(new WindowCloser());

       // Initialize the window size.

       setSize(800, 800);

       // Show the window.

       // show(); Using show() while JDK version is below 1.5.

       setVisible(true);

       // Fit the certain size.

       pack();

    }  

   

    public void actionPerformed(ActionEvent e) {

       Object target = e.getSource();

       String label = e.getActionCommand();

       if (target == reset)

           handleReset();

       else if (“0123456789.“.indexOf(label) 》 0)

           handleNumber(label);

       else

           handleOperator(label);

    }

    // Is the first digit pressed?

    boolean isFirstDigit = true;

    /**

     * Number handling.

     * @param key the key of the button.

     */

    public void handleNumber(String key) {

       if (isFirstDigit)

           display.setText(key);

       else if ((key.equals(“.“)) && (display.getText().indexOf(“.“) 《 0))

           display.setText(display.getText() + “.“);

       else if (!key.equals(“.“))

           display.setText(display.getText() + key);

       isFirstDigit = false;

    }

   

    /**

     * Reset the calculator.

     */

    public void handleReset() {

       display.setText(“0“);

       isFirstDigit = true;

       operator = “=“;

    }

 

    double number = 0.0;

    String operator = “=“;

   

    /**

     * Handling the operation.

     * @param key pressed operator’s key.

     */

    public void handleOperator(String key) {

       if (operator.equals(“+“))

           number += Double.valueOf(display.getText());

       else if (operator.equals(“-“))

           number -= Double.valueOf(display.getText());

       else if (operator.equals(“*“))

           number *= Double.valueOf(display.getText());

       else if (operator.equals(“/“))

           number /= Double.valueOf(display.getText());

       else if (operator.equals(“=“))

           number = Double.valueOf(display.getText());

       display.setText(String.valueOf(number));

       operator = key;

       isFirstDigit = true;

    }

   

    public static void main(String args) {

       new JCalculator();

    }

}

运行界面:


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.=/“;
ArrayList《String》 arrayList = new ArrayList《String》();//保存计算式,通过方法进行运算

public CalculatorA(){

frame = new JFrame(“我的计算器v1.1“);
frame.setLocation(300,300);

field = new JTextField(25);

allButtons = new JButton;
for(int i=0;i《allButtons.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;i《allButtons.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;i《allButtons.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 ArrayList《String》 getResult(ArrayList《String》 list){
String res = null;
String s = {“/“,“*“,“-“,“+“};
int i=0;
if(list.size()》1){
for(;i《s.length;){
if(s[i].equals(“/“)){
for(int j=0;j《list.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;j《list.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;j《list.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;j《list.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;k《c.length;k++){
c[k] = res.charAt(k);
}
for(int k=0;k《c.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

用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)就是类型转换了,下面都是一样-java

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放置在窗体的中间

}

}

直接复制 保存成Jisuanqi .java可以直接运行了


、使用JAVA语言编写一个简易的计算器


我写了个整数可以使用的, 你可以研究一下, 添入小数部分
功能和window7自带的那个一样
import java.awt.BorderLayout;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class Caculator extends JFrame {
private JLabel r1;
private JLabel r2;
private int tempResult;
boolean isResult;
private String lastOperator;
public Caculator() {
isResult = true;
tempResult = 0;
lastOperator = “+“;
JPanel jp_main = new JPanel();
jp_main.setLayout(new BorderLayout());
JPanel jp_show = new JPanel();
jp_show.setBorder(new LineBorder(java.awt.Color.black));
jp_show.setLayout(new GridLayout(2, 1));
r1 = new JLabel(“0“, JLabel.RIGHT);
r2 = new JLabel(“0“, JLabel.RIGHT);
jp_show.add(r1);
jp_show.add(r2);
JPanel jp_button = new JPanel();
jp_button.setBorder(new LineBorder(java.awt.Color.black));
jp_button.setLayout(new GridLayout(4, 4));
JButton one = new JButton(“1“);
JButton two = new JButton(“2“);
JButton three = new JButton(“3“);
JButton four = new JButton(“4“);
JButton five = new JButton(“5“);
JButton six = new JButton(“6“);
JButton seven = new JButton(“7“);
JButton eight = new JButton(“8“);
JButton nine = new JButton(“9“);
JButton zero = new JButton(“0“);
JButton dot = new JButton(“.“);
JButton plus = new JButton(“+“);
JButton sub = new JButton(“-“);
JButton multi = new JButton(“*“);
JButton divide = new JButton(“/“);
JButton result = new JButton(“=“);
jp_button.add(one);
jp_button.add(two);
jp_button.add(three);
jp_button.add(sub);
jp_button.add(four);
jp_button.add(five);
jp_button.add(six);
jp_button.add(multi);
jp_button.add(seven);
jp_button.add(eight);
jp_button.add(nine);
jp_button.add(divide);
jp_button.add(zero);
jp_button.add(dot);
jp_button.add(plus);
jp_button.add(result);
JPanel reset = new JPanel();
reset.setBorder(new LineBorder(java.awt.Color.black));
JButton rb = new JButton(“重置“);
rb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r1.setText(“0“);
r2.setText(“0“);
isResult = true;
tempResult = 0;
lastOperator = “+“;
}
});
reset.add(rb);
jp_main.add(jp_show, BorderLayout.NORTH);
jp_main.add(jp_button, BorderLayout.CENTER);
jp_main.add(reset, BorderLayout.SOUTH);
this.add(jp_main);
one.addActionListener(new NumberButtonListener());
two.addActionListener(new NumberButtonListener());
three.addActionListener(new NumberButtonListener());
four.addActionListener(new NumberButtonListener());
five.addActionListener(new NumberButtonListener());
six.addActionListener(new NumberButtonListener());
seven.addActionListener(new NumberButtonListener());
eight.addActionListener(new NumberButtonListener());
nine.addActionListener(new NumberButtonListener());
zero.addActionListener(new NumberButtonListener());
// dot.addActionListener(new NumberButtonListener());
plus.addActionListener(new OperatorButtonListener());
sub.addActionListener(new OperatorButtonListener());
multi.addActionListener(new OperatorButtonListener());
divide.addActionListener(new OperatorButtonListener());
result.addActionListener(new ResultButtonListener());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(370, 280);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
private class NumberButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JButton jb = (JButton) arg0.getSource();
String temp = r2.getText();
if (!isResult) {
if (temp.equals(“0“)) {
r2.setText(jb.getText());
} else {
r2.setText(temp + jb.getText());
}
} else {
r2.setText(jb.getText());
}
isResult = false;
}
}

private class ResultButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
r1.setText(“0“);
new OperatorButtonListener().caculate(new JButton(“+“));
r2.setText(String.valueOf(tempResult));
isResult = true;
tempResult = 0;
lastOperator = “+“;
}
}
private class OperatorButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JButton jb = (JButton) arg0.getSource();
String temp1 = r1.getText();
if (temp1.equals(“0“)) {
r1.setText(r2.getText() + “ “ + jb.getText());
caculate(jb);

} else {
r1.setText(temp1 + “ “ + r2.getText() + “ “ + jb.getText());
caculate(jb);
r2.setText(String.valueOf(tempResult));

}
isResult = true;
}

public void caculate(JButton jb){
if(lastOperator.equals(“+“)){
tempResult += Integer.valueOf(r2.getText());
}else if(lastOperator.equals(“-“)){
tempResult -= Integer.valueOf(r2.getText());
}else if(lastOperator.equals(“*“)){
tempResult *= Integer.valueOf(r2.getText());
}else if(lastOperator.equals(“/“)){
tempResult /= Integer.valueOf(r2.getText());
}
lastOperator = jb.getText();
}
}
}
下面是main函数
public class Test {
/**
* @param args
*/
public static void main(String args) {
// TODO Auto-generated method stub
Caculator c = new Caculator();
}
}
你运行就可以看到效果
-JAVA

用JAVA编写一个简单的计算器,要求如下:


然后 通过输入 显示结果,比如说:

以下是上图计算器的代码:

  • package Computer;  

  • import java.awt.BorderLayout;  

  • import java.awt.Color;  

  • import java.awt.Container;  

  • import java.awt.Font;  

  • import java.awt.GridLayout;  

  • import java.awt.event.ActionEvent;  

  • import java.awt.event.ActionListener;  

  • import java.util.Stack;  

  • import javax.swing.JApplet;  

  • import javax.swing.JButton;  

  • import javax.swing.JFrame;  

  • import javax.swing.JPanel;  

  • import javax.swing.JTextField;  

  • public class Count extends JApplet implements ActionListener  

  • {  

  • /** 

  • *  

  • */  

  • private static final long serialVersionUID = 1L;  

  • private JTextField textField = new JTextField(“请输入“);  

  • String operator = ““;//操作  

  • String input = ““;//输入的 式子  

  • boolean flag =  true;  

  • //  boolean flag1 = true;  

  • //  boolean flag2 = true;  

  • public void init()//覆写Applet里边的init方法  

  • {  

  • Container C = getContentPane();  

  • JButton b = new JButton;  

  • JPanel panel = new JPanel();  

  • C.add(textField, BorderLayout.NORTH);  

  • C.add(panel,BorderLayout.CENTER);  

  • panel.setLayout(new GridLayout(4, 4,5,5));  

  • String name={“7“,“8“,“9“,“+“,“4“,“5“,“6“,“-“,“1“,“2“,“3“,“*“,“0“,“C“,“=“,“/“};//设置 按钮  

  • for(int i=0;i《16;i++)//添加按钮  

  • {  

  • b[i] = new JButton(name[i]);  

  • b[i].setBackground(new Color(192,192,192));  

  • b[i].setForeground(Color.BLUE);//数字键 设置为 蓝颜色  

  • if(i%4==3)  

  • b[i].setForeground(Color.RED);  

  • b[i].setFont(new Font(“宋体“,Font.PLAIN,16));//设置字体格式  

  • panel.add(b[i]);  

  • b[i].addActionListener(this);  

  • }  

  • b.setForeground(Color.RED);//非数字键,即运算键设置为红颜色  

  • b.setForeground(Color.RED);  

  • }  

  • public void actionPerformed(ActionEvent e)   

  • {  

  • int cnt = 0;  

  • String actionCommand = e.getActionCommand();  

  • if(actionCommand.equals(“+“)||actionCommand.equals(“-“)||actionCommand.equals(“*“) ||actionCommand.equals(“/“))  -java

  • input +=“ “+actionCommand+“ “;//设置输入,把输入的样式改成 需要的样子  

  • else if(actionCommand.equals(“C“))  

  • input = ““;  

  • else if(actionCommand.equals(“=“))//当监听到等号时,则处理 input  

  • {  

  • input+= “=“+compute(input);  

  • textField.setText(input);  

  • input=““;  

  • cnt = 1;  

  • }  

  • else  

  • input += actionCommand;//数字为了避免多位数的输入 不需要加空格  

  • if(cnt==0)  

  • textField.setText(input);  

  • }  

  • private String compute(String input)//即1237 的 样例  

  • {  

  • String str;  

  • str = input.split(“ “);  

  • Stack《Double》 s = new Stack《Double》();  

  • double m = Double.parseDouble(str);  

  • s.push(m);  

  • for(int i=1;i《str.length;i++)  

  • {  

  • if(i%2==1)    

  • {    

  • if(str[i].compareTo(“+“)==0)    

  • {    

  • double help = Double.parseDouble(str[i+1]);    

  • s.push(help);    

  • }    

  • if(str[i].compareTo(“-“)==0)    

  • {    

  • double help = Double.parseDouble(str[i+1]);    

  • s.push(-help);    

  • }    

  • if(str[i].compareTo(“*“)==0)    

  • {    

  • double help = Double.parseDouble(str[i+1]);    

  • double ans = s.peek();//取出栈顶元素    

  • s.pop();//消栈    

  • ans*=help;    

  • s.push(ans);    

  • }    

  • if(str[i].compareTo(“/“)==0)    

  • {    

  • double help = Double.parseDouble(str[i+1]);    

  • double ans = s.peek();    

  • s.pop();    

  • ans/=help;    

  • s.push(ans);    

  • }    

  • }    

  • }    

  • double ans = 0d;    

  • while(!s.isEmpty())    

  • {    

  • ans+=s.peek();    

  • s.pop();    

  • }    

  • String result = String.valueOf(ans);  

  • return result;  

  • }  

  • public static void main(String args)  

  • {  

  • JFrame frame = new JFrame(“Count“);  

  • Count applet = new Count();  

  • frame.getContentPane().add(applet, BorderLayout.CENTER);  

  • applet.init();//applet的init方法  

  • applet.start();//线程开始  

  • frame.setSize(350, 400);//设置窗口大小  

  • frame.setVisible(true);//设置窗口可见  

  • }  

  • }  


如何用java编写一个简单的计算器,只要能进行最基本的加减乘除运算就可以了,本人急用,简单易懂即可,大


简单的啊,我有个自己编的完美的,不过给你改成简单的吧。有注释。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.text.*;
public class Calculator extends JFrame implements ActionListener
{
int m=0,i,n=0;
float sum=0,s1,s2,equ;
String v=““;
JPanel delete_main = new JPanel();
JPanel delete = new JPanel();
JPanel buttons = new JPanel();

JTextField text = new JTextField(“0“);
JButton backspace = new JButton(“Backspace“);
JButton c = new JButton(“C“);
JButton ce = new JButton(“CE“);
JButton bt1= new JButton(“1“);
JButton bt2= new JButton(“2“);
JButton bt3= new JButton(“3“);
JButton bt4= new JButton(“+“);
JButton bt5 = new JButton(“4“);
JButton bt6= new JButton(“5“);
JButton bt7= new JButton(“6“);
JButton bt8= new JButton(“-“);
JButton bt9= new JButton(“7“);
JButton bt10= new JButton(“8“);
JButton bt11= new JButton(“9“);
JButton bt12= new JButton(“*“);
JButton bt13= new JButton(“0“);
JButton bt14= new JButton(“.“);
JButton bt15= new JButton(“=“);
JButton bt16= new JButton(“/“);

public Calculator()
{
super(“简易计算器--超人不会飞荣誉出品“);
delete.setLayout(new GridLayout(1, 3, 15, 15));
delete.add(backspace);
delete.add(c);
delete.add(ce);
delete.setBorder(new LineBorder(delete.getBackground(), 5));//添加边框
c.addActionListener(this);
ce.addActionListener(this);
backspace.addActionListener(this);
text.setFont(new Font(“宋体“, Font.BOLD +Font.ITALIC, 20));
// 设置显示字体
text.setBackground(Color.getHSBColor(44, 3, 87));
text.setBorder(new LineBorder(Color.ORANGE, 1));
text.setHorizontalAlignment(SwingConstants.RIGHT); // 设置鼠标靠右
text.setEditable(false); // 屏蔽键盘输入,防止非法字符
delete_main.setLayout(new GridLayout(2, 1, 10, 10));
delete_main.add(text, BorderLayout.NORTH);
delete_main.add(delete, BorderLayout.SOUTH);
buttons.setLayout(new GridLayout(4, 5, 10, 20));

bt1.addActionListener(this); // 为各个按钮添加事件监听
buttons.add(bt1);
bt2.addActionListener(this);
buttons.add(bt2);
bt3.addActionListener(this);
buttons.add(bt3);
bt4.addActionListener(this);
buttons.add(bt4);
bt5.addActionListener(this);
buttons.add(bt5);
bt6.addActionListener(this);
buttons.add(bt6);
bt7.addActionListener(this);
buttons.add(bt7);
bt8.addActionListener(this);
buttons.add(bt8);
bt9.addActionListener(this);
buttons.add(bt9);
bt10.addActionListener(this);
buttons.add(bt10);
bt11.addActionListener(this);
buttons.add(bt11);
bt12.addActionListener(this);
buttons.add(bt12);
bt13.addActionListener(this);
buttons.add(bt13);
bt14.addActionListener(this);
buttons.add(bt14);
bt15.addActionListener(this);
buttons.add(bt15);
bt16.addActionListener(this);
buttons.add(bt16);

buttons.setBorder(new LineBorder(delete.getBackground(), 5));//边框
this.setLayout(new BorderLayout());
this.add(delete_main, BorderLayout.NORTH);
this.add(buttons, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //添加关闭窗口事件监听器
pack(); //自动设置窗体大小
setResizable(false); // 设置面板大小不可变
setVisible(true);
Toolkit tk = this.getToolkit();
Dimension de = tk.getScreenSize();
setBounds((de.width - this.getWidth()) / 2,(de.height - this.getHeight()) / 2, this.getWidth(), this.getHeight());
//使之居于屏幕正中央
}
public void actionPerformed(ActionEvent e)
{ //事件响应
//Object source = e.getSource();
if(e.getSource()==backspace) //退格键
{
v=v.substring(0,v.length() - 1);
text.setText(v);
}
if(e.getSource()==c||e.getSource()==ce) //清空键
{
m=0;
sum=0;
v=““;s1=0;s2=0;i=0;
text.setText(“0“);
}
if(e.getSource()==bt1)
{
if(m==1)
v=““;
v=v+“1“;
text.setText(v);
m=0;n=1;

}
if(e.getSource()==bt2)
{
if(m==1)
v=““;
v=v+“2“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt3)
{
if(m==1)
v=““;
v=v+“3“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt4) // +按钮
{
if(n==1) //如果按之前按了0~9数字键,就运算
{
sum=Float.parseFloat(v);

}
else //如果按之前没按0~9数字键,直接按了运算符,不做任何操作
{
}
i=1;
m=1;n=0;
}
if(e.getSource()==bt5)
{
if(m==1)
v=““;
v=v+“4“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt6)
{
if(m==1)
v=““;
v=v+“5“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt7)
{
if(m==1)
v=““;
v=v+“6“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt8) // -按钮
{
if(n==1)
{
sum=Float.parseFloat(v);

}
else
{
}
i=2;
m=1;n=0;
}
if(e.getSource()==bt9)
{
if(m==1)
v=““;
v=v+“7“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt10)
{
if(m==1)
v=““;
v=v+“8“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt11)
{
if(m==1)
v=““;
v=v+“9“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt12) //*按钮
{
if(n==1)
{
sum=Float.parseFloat(v);

}
else
{
}
i=3;
m=1;n=0;

}
if(e.getSource()==bt13)
{
if(m==1)
v=““;
v=v+“0“;
text.setText(v);
m=0;n=1;
}
if(e.getSource()==bt14)
{

}
if(e.getSource()==bt15) //等于按钮
{
if(m==1) // 如果输入了+=等非法输入,不做任何操作
{ }
else
{
s1=sum;
s2=Float.parseFloat(v);
switch(i)
{
case 0: //如果按过数字键后直接按等号,直接输出
equ=Float.parseFloat(v);
break;
case 1:
equ=s1+s2;
break;
case 2:
equ=s1-s2;
break;
case 3:
equ=s1*s2;
break;
case 4:
equ=s1/s2;
break;
}

sum=0;v=““; //清空运算数
v=String.valueOf(equ);
text.setText(String.valueOf(equ));
i=0;
}
}
if(e.getSource()==bt16) // 除按钮
{
if(n==1)
{
sum=Float.parseFloat(v);

}
else
{
}
i=4;
m=1;n=0;
}

}
public static void main(String args)
{
Calculator bt=new Calculator();
}
}
-JAVA

用java编写简易计算器


package calc; import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*; public class Caculator {
private JFrame jf;
private JButton jbs;
private JTextField jtf;
private JButton clear;
private double num1, num2, rs;
private char c;
/**
* 构造方法实例化属性
*/
public Caculator() {
jf = new JFrame(“简易计算器“);
jtf = new JTextField(20);
clear = new JButton(“clear“);
jbs = new JButton;
String str = “123+456-789*0./=“;
for (int i = 0; i 《 str.length(); i++) {
jbs[i] = new JButton(str.charAt(i) + ““);
}
init();
addEventHandler();
showMe();
}
/**
* 布局图形界面
*/
public void init() {
JPanel jp1 = new JPanel();
jp1.add(jtf); JPanel jp2 = new JPanel();
jp2.setLayout(new GridLayout(4, 4));
for (int i = 0; i 《 16; i++) {
jp2.add(jbs[i]);
}
JPanel jp3 = new JPanel();
jp3.add(clear);
jf.add(jp1, BorderLayout.NORTH);
jf.add(jp2, BorderLayout.CENTER);
jf.add(jp3, BorderLayout.SOUTH);
} public void setFont() { }
public void setColor() { }
public void addEventHandler() {
ActionListener lis = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton) e.getSource();
String str = jb.getText().trim();// 把字符串的首尾空格去掉!
if (“0123456789.“.indexOf(str) != -1) {// 如果是数字或点号
jtf.setText(jtf.getText() + str);
return;
}
if (“+-*/“.indexOf(str) != -1) {
num1 = Double.parseDouble(jtf.getText());
jtf.setText(““);
c = str.charAt(0);
jtf.setText(““);
return;
}
if (str.equals(“=“)) {
num2 = Double.parseDouble(jtf.getText());
switch (c) {
case ’+’:
rs = num1 + num2;
break;
case ’-’:
rs = num1 - num2;
break;
case ’*’:
rs = num1 * num2;
break;
case ’/’:
rs = num1 / num2;
break;
}
jtf.setText(Double.toString(rs));
return;
}
if (e.getActionCommand().equals(“clear“)) {
jtf.setText(““);
return;
}
}
};
for (int i = 0; i 《 jbs.length; i++) { jbs[i].addActionListener(lis);
}
clear.addActionListener(lis);
}
public void showMe() {
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args) {
new Caculator();
}
}
呃.貌似有小Bug..自己改进一下吧..好运哈..
-java

用java编写简单计算器


这个是我以前写的一个程序 我把里边没用的注掉了 如果你想添加其他功能 把注释解开就行了
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;
constraints.weightx = 100;
constraints.weighty = 100;
layout.setConstraints(displayField, constraints);
container.add(displayField);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// addButton(“Backspace“, 0, 1, 2, 1, insert);
// addButton(“CE“, 2, 1, 1, 1, insert);
// addButton(“C“, 3, 1, 1, 1, insert);
addButton(“7“, 0, 2, 1, 1, insert);
addButton(“8“, 1, 2, 1, 1, insert);
addButton(“9“, 2, 2, 1, 1, insert);
addButton(“/“, 3, 2, 1, 1, command);
addButton(“4“, 0, 3, 1, 1, insert);
addButton(“5“, 1, 3, 1, 1, insert);
addButton(“6“, 2, 3, 1, 1, insert);
addButton(“*“, 3, 3, 1, 1, command);
addButton(“1“, 0, 4, 1, 1, insert);
addButton(“2“, 1, 4, 1, 1, insert);
addButton(“3“, 2, 4, 1, 1, insert);
addButton(“-“, 3, 4, 1, 1, command);
addButton(“0“, 0, 5, 1, 1, insert);
// addButton(“+/-“, 1, 5, 1, 1, insert);// 只显示“-“号,“+“没有实用价值
addButton(“.“, 2, 5, 1, 1, insert);
addButton(“+“, 3, 5, 1, 1, command);
addButton(“=“, 0, 6, 4, 1, command);
this.setResizable(false);
setSize(180, 200);
setVisible(true);
}
private void addButton(String label, int row, int column, int with,
int height, ActionListener listener) {
JButton button = new JButton(label);
constraints.gridx = row;
constraints.gridy = column;
constraints.gridwidth = with;
constraints.gridheight = height;
constraints.fill = GridBagConstraints.BOTH;
button.addActionListener(listener);
layout.setConstraints(button, constraints);
container.add(button);
}
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
displayField.setText(““);
start = false;
if (input.equals(“+/-“))
displayField.setText(displayField.getText() + “-“);
}
if (!input.equals(“+/-“)) {
if (input.equals(“Backspace“)) {
String str = displayField.getText();
if (str.length() 》 0)
displayField
.setText(str.substring(0, str.length() - 1));
} else if (input.equals(“CE“) || input.equals(“C“)) {
displayField.setText(“0“);
start = true;
} else
displayField.setText(displayField.getText() + input);
}
}
}
private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
if (start) {
lastCommand = command;
} else {
calculate(Double.parseDouble(displayField.getText()));
lastCommand = command;
start = true;
}
}
}
public void calculate(double x) {
if (lastCommand.equals(“+“))
result += x;
else if (lastCommand.equals(“-“))
result -= x;
else if (lastCommand.equals(“*“))
result *= x;
else if (lastCommand.equals(“/“))
result /= x;
else if (lastCommand.equals(“=“))
result = x;
displayField.setText(““ + result);
}
public static void main(String args) {
Calculator calculator = new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
-JAVA

JAVA编写简单的计算器


import java.awt.BorderLayout;
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;
public class Test implements ActionListener {
String str;
String fuhao;
double count1 = 0;
double count2 = 0;
JFrame jf = new JFrame(“计算器“);
JTextField jtf = new JTextField(10);
int a, b;
public Test() {
JPanel jp = new JPanel();
String lab = { “backs“, “ce“, “c“, “=“, “7“, “8“, “9“, “+“, “4“, “5“,
“6“, “-“, “1“, “2“, “3“, “*“, “0“, “.“, “+/-“, “/“ };
jp.setLayout(new GridLayout(5, 4));
JButton jb = new JButton[lab.length];
jf.add(jtf, BorderLayout.NORTH);
for (int i = 0; i 《 jb.length; i++) {
jb[i] = new JButton(lab[i]);
jp.add(jb[i]);
}
for (int i = 0; i 《 20; i++) {
jb[i].addActionListener(this);
}
jf.add(jp);// 默认放在center
jf.setSize(300, 200);
jf.setLocation(350, 250);
jf.setResizable(false);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
String com = ae.getActionCommand();
double result = 0;
if (com.equals(“+/-“)) {
jtf.setText(“-“ + jtf.getText());
}
if (com.equals(“backs“)) {
String s = jtf.getText();
if (str.length() 》 0) {
jtf.setText(s.substring(0, s.length() - 1));
}
}
if (com.equals(“ce“) || com.equals(“c“)) {
jtf.setText(“0“);
}
if (“+“.equals(com)) {
fuhao = com;
count1 = Double.parseDouble(jtf.getText());
str = jtf.getText() + com;
jtf.setText(str);
}
if (“-“.equals(com)) {
fuhao = com;
count1 = Double.parseDouble(jtf.getText());
str = jtf.getText() + com;
jtf.setText(str);
}
if (“*“.equals(com)) {
fuhao = com;
count1 = Double.parseDouble(jtf.getText());
str = jtf.getText() + com;
jtf.setText(str);
}
if (“/“.equals(com)) {
fuhao = com;
count1 = Double.parseDouble(jtf.getText());
str = jtf.getText() + com;
jtf.setText(str);
}
if (“0“.equals(com) || “1“.equals(com) || “2“.equals(com)
|| “3“.equals(com) || “4“.equals(com) || “5“.equals(com)
|| “6“.equals(com) || “7“.equals(com) || “8“.equals(com)
|| “9“.equals(com)) {
jtf.setText(jtf.getText() + com);
}
if (“=“.equals(com)) {
str = jtf.getText() + com;
count2 = Double.parseDouble(str.substring(str.indexOf(fuhao) + 1,
str.length() - 1));
if (“+“.equals(fuhao))
result = count1 + count2;
if (“-“.equals(fuhao))
result = count1 - count2;
if (“*“.equals(fuhao))
result = count1 * count2;
if (“/“.equals(fuhao))
result = count1 / count2;
jtf.setText(result + ““);
}
}
// TODO Auto-generated method stub
public static void main(String args) {
new Test();
}
}
-java

怎么用JAVA编程编写一个计算器


  1. 打开IED:打开自己java编程的软件,采用的是eclipse软件。

  2. 建立java工程。

  3. 编写类。

编写类的详细步骤

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;i《jba.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){

jtf.setText(add(jtf.getText()));

ifOp=true;

}

else if(e.getSource()==jba){

jtf.setText(subtract(jtf.getText()));

ifOp=true;

}

else if(e.getSource()==jba){

jtf.setText(multiply(jtf.getText()));

ifOp=true;

}

else if(e.getSource()==jba){

jtf.setText(divide(jtf.getText()));

ifOp=true;

}

else if(e.getSource()==jba){

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();

}