Java入门写一个计算器的程序,要求如图
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java入门写一个计算器的程序,要求如图相关的知识,希望对你有一定的参考价值。
import java.awt.*;import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.LinkedList; //工具包
import java.text.NumberFormat; //文本包
/**
* java swing计算器
* @author young
*
*/
public class Calculator extends Frame implements ActionListener // 计算器类
JTextField result;
NumberButton numberButton[];
OperatorButton operatorButton[];
Button radixpoint, positiveminus, backspace, reciprocal, equal, clear; // 声明成员变量
// 小数点按钮,正负号按钮,退格按钮,求倒数按钮,等号按钮,清零按钮
Panel panel;
String operator[] = "+", "-", "*", "/" ;
LinkedList linklist;
boolean pressequal = false;
public Calculator() // 构造方法
super("计算器");
linklist = new LinkedList();
numberButton = new NumberButton[10];
for (int i = 0; i <= 9; i++)
numberButton[i] = new NumberButton(i);
numberButton[i].addActionListener(this);
operatorButton = new OperatorButton[4];
for (int i = 0; i < 4; i++)
operatorButton[i] = new OperatorButton(operator[i]);
operatorButton[i].addActionListener(this);
radixpoint = new Button(".");
positiveminus = new Button("+/-");
backspace = new Button("CE");
reciprocal = new Button("1/x");
equal = new Button("=");
clear = new Button("C");
radixpoint.setForeground(Color.red);
positiveminus.setForeground(Color.red);
backspace.setForeground(Color.red);
reciprocal.setForeground(Color.red);
equal.setForeground(Color.red);
clear.setForeground(Color.red);
radixpoint.addActionListener(this);
positiveminus.addActionListener(this);
backspace.addActionListener(this);
reciprocal.addActionListener(this);
equal.addActionListener(this);
clear.addActionListener(this);
result = new JTextField(10);
result.setHorizontalAlignment(JTextField.RIGHT);
result.setForeground(Color.black);
result.setBackground(Color.white);
result.setFont(new Font("TimesRoman", Font.PLAIN, 14));
result.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
result.setEditable(false);
panel = new Panel();
panel.setLayout(new GridLayout(4, 5));
panel.add(numberButton[1]);
panel.add(numberButton[2]);
panel.add(numberButton[3]);
panel.add(backspace);
panel.add(clear);
panel.add(numberButton[4]);
panel.add(numberButton[5]);
panel.add(numberButton[6]);
panel.add(operatorButton[0]);
panel.add(operatorButton[2]);
panel.add(numberButton[7]);
panel.add(numberButton[8]);
panel.add(numberButton[9]);
panel.add(operatorButton[1]);
panel.add(operatorButton[3]);
panel.add(numberButton[0]);
panel.add(positiveminus);
panel.add(reciprocal);
panel.add(radixpoint);
panel.add(equal);
add(result, "North");
add(panel, "Center");
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
);
setSize(270, 200);
setLocation(300, 230);
setVisible(true);
public void actionPerformed(ActionEvent e) // 按钮的单击事件处理方法
if (e.getSource() instanceof NumberButton) // 数字按钮
NumberButton b = (NumberButton) e.getSource();
if (linklist.size() == 0)
int number = b.getNumber();
linklist.add("" + number);
result.setText("" + number);
pressequal = false;
else if (linklist.size() == 1 && pressequal == false)
int number = b.getNumber();
String num = (String) linklist.getFirst();
String s = num.concat("" + number);
linklist.set(0, s);
result.setText(s);
else if (linklist.size() == 1 && pressequal == true)
int number = b.getNumber();
linklist.removeFirst();
linklist.add("" + number);
pressequal = false;
result.setText("" + number);
else if (linklist.size() == 2)
int number = b.getNumber();
linklist.add("" + number);
result.setText("" + number);
else if (linklist.size() == 3)
int number = b.getNumber();
String num = (String) linklist.getLast();
String s = num.concat("" + number);
linklist.set(2, s);
result.setText(s);
else if (e.getSource() instanceof OperatorButton) // 操作按钮
OperatorButton b = (OperatorButton) e.getSource();
if (linklist.size() == 1)
String fuhao = b.getOperator();
linklist.add(fuhao);
else if (linklist.size() == 2)
String fuhao = b.getOperator();
linklist.set(1, fuhao);
else if (linklist.size() == 3)
String fuhao = b.getOperator();
String number1 = (String) linklist.getFirst();
String number2 = (String) linklist.getLast();
String operator = (String) linklist.get(1);
try
double n1 = Double.parseDouble(number1);
double n2 = Double.parseDouble(number2);
double n = 0;
if (operator.equals("+"))
n = n1 + n2;
else if (operator.equals("-"))
n = n1 - n2;
else if (operator.equals("*"))
n = n1 * n2;
else if (operator.equals("/"))
n = n1 / n2;
linklist.clear();
linklist.add("" + n);
linklist.add(fuhao);
result.setText("" + n);
catch (Exception ee)
else if (e.getSource() == equal) // 等号按钮
pressequal = true;
if (linklist.size() == 1 || linklist.size() == 2)
String num = (String) linklist.getFirst();
result.setText("" + num);
else if (linklist.size() == 3)
String number1 = (String) linklist.getFirst();
String number2 = (String) linklist.getLast();
String operator = (String) linklist.get(1);
try
double n1 = Double.parseDouble(number1);
double n2 = Double.parseDouble(number2);
double n = 0;
if (operator.equals("+"))
n = n1 + n2;
else if (operator.equals("-"))
n = n1 - n2;
else if (operator.equals("*"))
n = n1 * n2;
else if (operator.equals("/"))
n = n1 / n2;
result.setText("" + n);
linklist.set(0, "" + n);
linklist.removeLast();
linklist.removeLast();
catch (Exception ee)
else if (e.getSource() == radixpoint) // 小数点按钮
if (linklist.size() == 0)
pressequal = false;
else if (linklist.size() == 1)
String dot = radixpoint.getLabel();
String num = (String) linklist.getFirst();
String s = null;
if (num.indexOf(dot) == -1)
s = num.concat(dot);
linklist.set(0, s);
else
s = num;
linklist.set(0, s);
result.setText(s);
else if (linklist.size() == 3)
String dot = radixpoint.getLabel();
String num = (String) linklist.getLast();
String s = null;
if (num.indexOf(dot) == -1)
s = num.concat(dot);
linklist.set(2, s);
else
s = num;
result.setText(s);
else if (e.getSource() == backspace) // 退格按钮
if (linklist.size() == 1)
String num = (String) linklist.getFirst();
if (num.length() >= 1)
num = num.substring(0, num.length() - 1);
linklist.set(0, num);
result.setText(num);
else
linklist.removeLast();
result.setText("0");
else if (linklist.size() == 3)
String num = (String) linklist.getLast();
if (num.length() >= 1)
num = num.substring(0, num.length() - 1);
linklist.set(2, num);
result.setText(num);
else
linklist.removeLast();
result.setText("0");
else if (e.getSource() == positiveminus) // 正负号按钮
if (linklist.size() == 1)
String number1 = (String) linklist.getFirst();
try
double d = Double.parseDouble(number1);
d = -1 * d;
String str = String.valueOf(d);
linklist.set(0, str);
result.setText(str);
catch (Exception ee)
else if (linklist.size() == 3)
String number2 = (String) linklist.getLast();
try
double d = Double.parseDouble(number2);
d = -1 * d;
String str = String.valueOf(d);
linklist.set(2, str);
result.setText(str);
catch (Exception ee)
else if (e.getSource() == reciprocal) // 求倒数按钮
if (linklist.size() == 1 || linklist.size() == 2)
String number1 = (String) linklist.getFirst();
try
double d = Double.parseDouble(number1);
d = 1.0 / d;
String str = String.valueOf(d);
linklist.set(0, str);
result.setText(str);
catch (Exception ee)
else if (linklist.size() == 3)
String number2 = (String) linklist.getLast();
try
double d = Double.parseDouble(number2);
d = 1.0 / d;
String str = String.valueOf(d);
linklist.set(0, str);
result.setText(str);
catch (Exception ee)
else if (e.getSource() == clear) // 清零按钮
pressequal = false;
result.setText("0");
linklist.clear();
public static void main(String args[])
new Calculator();
class NumberButton extends Button // 数字按钮类
int number;
public NumberButton(int number) // 构造方法
super("" + number);
this.number = number;
setForeground(Color.blue);
public int getNumber()
return number;
class OperatorButton extends Button // 运算符号按钮类
String operator;
public OperatorButton(String operator) // 构造方法
super(operator);
this.operator = operator;
setForeground(Color.red);
public String getOperator()
return operator;
这就是代码了。
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
/**
* 我的计算器。Cheshi 继承于 JFrame,是计算器的界面
c*/
public class Cheshi extends JFrame
private Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox = new JTextField("0");
private CalculatorCore core = new CalculatorCore();
private ActionListener listener = new ActionListener()
public void actionPerformed(ActionEvent e)
JButton b = (JButton) e.getSource();
String label = b.getText();
String result = core.process(label);
textbox.setText(result);
;
public Cheshi(String title) throws HeadlessException
super(title); // 调用父类构造方法
setupFrame(); // 调整窗体属性
setupControls(); // 创建控件
private void setupControls()
setupDisplayPanel(); // 创建文本面板
setupButtonsPanel(); // 创建按钮面板
// 创建按钮面板并添加按钮
private void setupButtonsPanel()
JPanel panel = new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]
"7", "8", "9", "+", "C",
"4", "5", "6", "-", "CE",
"1", "2", "3", "*", "", // 空字符串表示这个位置没有按钮
"0", ".", "=", "/", ""
);
this.add(panel, BorderLayout.CENTER);
/**
* 在指定的面板上创建按钮
*
* @param panel 要创建按钮的面板
* @param labels 按钮文字
*/
private void createButtons(JPanel panel, String[] labels)
for (String label : labels)
// 如果 label 为空,则表示创建一个空面板。否则创建一个按钮。
if (label.equals(""))
panel.add(new JPanel());
else
JButton b = new JButton(label);
b.addActionListener(listener); // 为按钮添加侦听器
panel.add(b);
// 设置显示面板,用一个文本框来作为计算器的显示部分。
private void setupDisplayPanel()
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
// 调整文本框
private void setupTextbox()
textbox.setHorizontalAlignment(JTextField.RIGHT); // 文本右对齐
textbox.setEditable(false); // 文本框只读
textbox.setBackground(Color.white); // 文本框背景色为白色
// 调整窗体
private void setupFrame()
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 当窗体关闭时程序结束
this.setLocation(100, 50); // 设置窗体显示在桌面上的位置
this.setSize(300, 200); // 设置窗体大小
this.setResizable(false); // 窗体大小固定
// 程序入口
public static void main(String[] args) throws Exception
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Cheshi frame = new Cheshi("我的计算器");
frame.setVisible(true); // 在桌面上显示窗体
/**
* 计算器核心逻辑。这个逻辑只能处理 1~2 个数的运算。
*/
class CalculatorCore
private String displayText = "0"; // 要显示的文本
boolean reset = true;
private BigDecimal number1, number2;
private String operator;
private HashMap<String, Operator> operators = new HashMap<String, Operator>();
private HashMap<String, Processor> processors = new HashMap<String, Processor>();
CalculatorCore()
setupOperators();
setupProcessors();
// 为每种命令添加处理方式
private void setupProcessors()
processors.put("[0-9]", new Processor()
public void calculate(String command)
numberClicked(command);
);
processors.put("\\.", new Processor()
public void calculate(String command)
dotClicked();
);
processors.put("=", new Processor()
public void calculate(String command)
equalsClicked();
);
processors.put("[+\\-*/]", new Processor()
public void calculate(String command)
operatorClicked(command);
);
processors.put("C", new Processor()
public void calculate(String command)
clearClicked();
);
processors.put("CE", new Processor()
public void calculate(String command)
clearErrorClicked();
);
// 为每种 operator 添加处理方式
private void setupOperators()
operators.put("+", new Operator()
public BigDecimal process(BigDecimal number1, BigDecimal number2)
return number1.add(number2);
);
operators.put("-", new Operator()
public BigDecimal process(BigDecimal number1, BigDecimal number2)
return number1.subtract(number2);
);
operators.put("*", new Operator()
public BigDecimal process(BigDecimal number1, BigDecimal number2)
return number1.multiply(number2);
);
operators.put("/", new Operator()
public BigDecimal process(BigDecimal number1, BigDecimal number2)
return number1.divide(number2, 30, RoundingMode.HALF_UP);
);
// 根据命令处理。这里的命令实际上就是按钮文本。
public String process(String command)
for (String pattern : processors.keySet())
if (command.matches(pattern))
processors.get(pattern).calculate(command);
break;
return displayText;
// 当按下 CE 时
private void clearErrorClicked()
if (operator == null)
number1 = null;
else
number2 = null;
displayText = "0";
reset = true;
// 当按下 C 时,将计算器置为初始状态。
private void clearClicked()
number1 = null;
number2 = null;
operator = null;
displayText = "0";
reset = true;
// 当按下 = 时
private void equalsClicked()
calculateResult();
number1 = null;
number2 = null;
operator = null;
reset = true;
// 计算结果
private void calculateResult()
number2 = new BigDecimal(displayText);
Operator oper = operators.get(operator);
if (oper != null)
BigDecimal result = oper.process(number1, number2);
displayText = result.toString();
// 当按下 +-*/ 时(这里也可以扩展成其他中间操作符)
private void operatorClicked(String command)
if (operator != null)
calculateResult();
number1 = new BigDecimal(displayText);
operator = command;
reset = true;
// 当按下 . 时
private void dotClicked()
if (displayText.indexOf(".") == -1)
displayText += ".";
else if (reset)
displayText = "0.";
reset = false;
// 当按下 0-9 时
private void numberClicked(String command)
if (reset)
displayText = command;
else
displayText += command;
reset = false;
// 运算符处理接口
interface Operator
BigDecimal process(BigDecimal number1, BigDecimal number2);
// 按钮处理接口
interface Processor
void calculate(String command);
适合初学者入门Java程序
相思一夜梅花发,忽到窗前疑是君。
概述
Java
是在IT
行业广泛使用的最流行的编程语言之一。它简单,健壮,可帮助我们重用代码。在本文中,让我们看一些了解Java
基础的应用程序。
入门的Java程序
计算机程序
编写一个Java
程序来执行基本的计算器操作。
当你考虑使用计算器时,就会想到加,减,乘,除等运算。让我们借助以下程序来实现基本的计算器操作。
package com.niocoder;
import java.util.Scanner;
/**
* Created by zhenglongfei on 2020/4/21
*
* @VERSION 1.0
*/
public class _01Calculator {
public static void main(String[] args) {
Scanner param = new Scanner(System.in);
System.out.print("请输入第一个数字:");
double first = param.nextDouble();
System.out.print("请输入第二个数字:");
double second = param.nextDouble();
System.out.print("请输入运算符 (+, -, *, /): ");
char operator = param.next().charAt(0);
double result;
//switch case for each of the operations
switch (operator) {
case ‘+‘:
result = first + second;
break;
case ‘-‘:
result = first - second;
break;
case ‘*‘:
result = first * second;
break;
case ‘/‘:
result = first / second;
break;
default:
// operator doesn‘t match any case constant (+, -, *, /)default:
System.out.println("Error! operator is not correct");
return;
}
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}
执行上述程序时,输出如下所示:
请输入第一个数字:10
请输入第二个数字:10
请输入运算符 (+, -, *, /): +
10.0 + 10.0 = 20.0
使用递归的阶乘程序
编写一个Java
程序来计算一个数字的阶乘。
数字的阶乘是所有小于或等于该数字的正数的乘积。n
的阶乘由n!
表示。现在,让我们编写一个程序,并使用递归查找数字的阶乘。
package com.niocoder;
import java.util.Scanner;
/**
* Created by zhenglongfei on 2020/4/21
*
* @VERSION 1.0
*/
public class _02Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个数字:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("输入数字的阶乘是: " + factorial);
}
static int fact(int number) {
if (number == 1) {
return 1;
}
return number * fact(number - 1);
}
}
执行上面的程序时,您将获得一个数字的阶乘,如下所示:
请输入一个数字:12
输入数字的阶乘是: 479001600
斐波纳契数列的程序
编写一个Java
程序来计算斐波那契数列直到n
个数字。
它是一个级数,其中下一项是前两项之和。例如:0 1 1 2 3 5 8 13……让我们编写一个Java
程序来计算斐波那契数列。
package com.niocoder;
import java.util.Scanner;
/**
* Created by zhenglongfei on 2020/4/21
*
* @VERSION 1.0
*/
public class _03Fibonacci {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个数字:");
//Stored the entered value in variable
int num = scanner.nextInt();
int first = 0, second = 1;
System.out.print(num + ":");
while (first < num) {
System.out.print(first + "+");
int sum = first + second;
first = second;
second = sum;
}
}
}
执行上述代码后,输出如下所示:
请输入一个数字:100
100:0+1+1+2+3+5+8+13+21+34+55+89+
字符串的回文程序
编写一个Java
程序来找出给定的字符串是否是回文。
回文是一个数字、字符串或序列,即使你颠倒了顺序,它们也是一样的。例如,RACECAR
,如果向后拼写将与RACECAR
相同。
package com.niocoder;
import java.util.Scanner;
/**
* Created by zhenglongfei on 2020/4/21
*
* @VERSION 1.0
*/
public class _04Palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个字符串: ");
String str = sc.nextLine();
checkPalindrome(str);
}
private static void checkPalindrome(String str) {
boolean flag = true;
int length = str.length();
for (int i = 0; i <= length / 2; i++) {
if (str.charAt(i) != str.charAt(length - i - 1)) {
flag = false;
break;
}
}
System.out.println(str + " 是否回文 = " + flag);
}
}
运行代码时,它将检查给定的字符串是否是回文,如下所示:
请输入一个字符串: abab
abab 是否回文 = false
请输入一个字符串: abba
abba 是否回文 = true
图案程序
用Java
编写程序打印菱形图案。
在这里,使用for
循环来打印菱形图案。
package com.niocoder;
import java.util.Scanner;
/**
* Created by zhenglongfei on 2020/4/21
*
* @VERSION 1.0
*/
public class _05DiamondPattern {
public static void main(String[] args) {
int n, i, j, space = 1;
System.out.print("请输入行数: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
space = n - 1;
for (j = 1; j <= n; j++) {
for (i = 1; i <= space; i++) {
System.out.print(" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++) {
System.out.print("*");
}
System.out.println("");
}
space = 1;
for (j = 1; j <= n - 1; j++) {
for (i = 1; i <= space; i++) {
System.out.print(" ");
}
space++;
for (i = 1; i <= 2 * (n - j) - 1; i++) {
System.out.print("*");
}
System.out.println("");
}
}
}
输出
请输入行数: 5
*
***
*****
*******
*********
*******
*****
***
*
字符串反转程序
编写一个Java程序来反转给定字符串中的字母。
这个Java
程序会反转用户输入的字符串中存在的字母。例如,“ Hello People
”将被称为“ olleH elpoeP
”。让我们使用Java
来实现相同的功能。
package com.niocoder;
/**
* Created by zhenglongfei on 2020/4/21
*
* @VERSION 1.0
*/
public class _06Stringreverse {
public static void main(String[] args) {
String str = "Welcome To niocoder";
String[] strArray = str.split(" ");
for (String temp : strArray) {
System.out.println(temp);
}
for (int i = 0; i < 3; i++) {
char[] s1 = strArray[i].toCharArray();
for (int j = s1.length - 1; j >= 0; j--) {
System.out.print(s1[j]);
}
System.out.print(" ");
}
}
}
上面程序的输出如下所示:
Welcome
To
niocoder
emocleW oT redocoin
镜像程序
编写一个Java程序来检查给定的数组是否为镜像数组。
package com.niocoder;
/**
* Created by zhenglongfei on 2020/4/21
*
* @VERSION 1.0
*/
public class _07MirrorInverse {
public static void main(String[] args) {
int arr[] = {3,4,2,0,1};
if (isMirrorInverse(arr))
System.out.println("Yes");
else
System.out.println("No");
}
static boolean isMirrorInverse(int arr[]) {
for (int i = 0; i < arr.length; i++) {
if (arr[arr[i]] != i)
return false;
}
return true;
}
}
输出
Yes
以上是关于Java入门写一个计算器的程序,要求如图的主要内容,如果未能解决你的问题,请参考以下文章
用java 编写一个程序,要求输入圆的半径,求圆的周长,面积.