如何用JAVA语言编写计算器小程序?

如何用JAVA语言编写计算器小程序?,第1张

具体代码如下:

import javax.swing.*

import java.awt.event.*

import java.awt.*

public class Calculator  extends JFrame implements ActionListener  {

private JFrame jf

private JButton[] allButtons

private JButton clearButton

private JTextField jtf

public Calculator() {

//对图形组件实例化

jf=new JFrame("任静的计算器1.0:JAVA版")

jf.addWindowListener(new WindowAdapter(){

public void windowClosing(){

System.exit(0)

}

})

allButtons=new JButton[16]

clearButton=new JButton("清除")

jtf=new JTextField(25)

jtf.setEditable(false)

String str="123+456-789*0.=/"

for(int i=0i<allButtons.lengthi++){

allButtons[i]=new JButton(str.substring(i,i+1))

}

}

public void init(){

//完成布局

jf.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(jtf)

for(int i=0i<16i++){

centerPanel.add(allButtons[i])

}

southPanel.add(clearButton)

jf.add(northPanel,BorderLayout.NORTH)

jf.add(centerPanel,BorderLayout.CENTER)

jf.add(southPanel,BorderLayout.SOUTH)

addEventHandler()

}

//添加事件监听

public void addEventHandler(){

jtf.addActionListener(this)

for(int i=0i<allButtons.lengthi++){

allButtons[i].addActionListener(this)

}

clearButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

Calculator.this.jtf.setText("")

}

})

}

//事件处理

public void actionPerformed(ActionEvent e) {

//在这里完成事件处理  使计算器可以运行

String action=e.getActionCommand()

if(action=="+"||action=="-"||action=="*"||action=="/"){

}

}

public void setFontAndColor(){

Font f=new Font("宋体",Font.BOLD,24)

jtf.setFont(f)

jtf.setBackground(new Color(0x8f,0xa0,0xfb))

for(int i=0i<16i++){

allButtons[i].setFont(f)

allButtons[i].setForeground(Color.RED)

}

}

public void showMe(){

init()

setFontAndColor()

jf.pack()

jf.setVisible(true)

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

}

public static void main(String[] args){

new Calculator().showMe()

}

}

主要涉及的知识点: 类的写法, 以及方法的调用 .建议多做练习. 如果有看不懂的地方. 可以继续追问,一起讨论.

参考代码如下

//Number类

class Number {

private int n1//私有的整型数据成员n1

private int n2//私有的整型数据成员n2

// 通过构造函数给n1和n2赋值

public Number(int n1, int n2) {

this.n1 = n1

this.n2 = n2

}

// 加法

public int addition() {

return n1 + n2

}

// 减法

public int subtration() {

return n1 - n2

}

// 乘法

public int multiplication() {

return n1 * n2

}

// 除法 (可能除不尽,所以使用double作为返回类型)

public double division() {

return n1 * 1.0 / n2 // 通过n1*1.0 把计算结果转换成double类型.

}

}

//Exam4 类

public class Exam4{

public static void main(String[] args) {

Number number=new Number(15, 6)//创建Number类的对象

//下面的是调用方法得到返回值进行输出显示

System.out.println("加法"+number.addition())

System.out.println("减法"+number.subtration())

System.out.println("乘法"+number.multiplication())

System.out.println("除法"+number.division())

}

}

/*

* @(#)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()

}

}

运行界面:


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/11087835.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-13
下一篇 2023-05-13

发表评论

登录后才能评论

评论列表(0条)

保存