search
HomeJavajavaTutorialSummary of common methods for writing calculators in Java

The examples in this article summarize common methods of writing calculators in Java. Share it with everyone for your reference, the details are as follows:

Method one:

package wanwa;
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);
}
}

Method two:

import java.awt.*;
import java.awt.event.*;
public class MyCalculator {
 PRivate Frame f;
 private TextField tf = new TextField(30);
 private long result;
 private boolean append=false;
 private char Operator='=';
 private Button[] btn=new Button[15];
 public MyCalculator() {
  initComponent();
 }
 private void initComponent() {
  f = new Frame("My Calculator V1.0");
  f.setLayout(new BorderLayout()); //The frame uses BorderLayout
  f.addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent evt) {
    System.exit(0);
   }
  });
  Panel centerPanel = new Panel();
  centerPanel.setLayout(new GridLayout(5, 3)); //The panel uses GridLayout
  NumberListener nl=new NumberListener();
  OperatorListener ol=new OperatorListener();
  btn[10]=new Button("+");
  btn[11]=new Button("-");
  btn[12]=new Button("*");
  btn[13]=new Button("/");
  btn[14]=new Button("=");
  for (int i=0;i<=9;i++){
   btn[i]=new Button(String.valueOf(i));
   centerPanel.add(btn[i]);
   btn[i].addActionListener(nl);
   if (i%2==1){
    centerPanel.add(btn[(i+19)/2]);
    btn[(i+19)/2].addActionListener(ol);
   }
  }
  f.add(centerPanel, BorderLayout.CENTER);
  Panel northPanel = new Panel();
  tf.setEditable(false);
  northPanel.add(tf);
  f.add(northPanel, BorderLayout.NORTH);
 }
 public void go() {
  f.pack();
  f.setVisible(true);
 }
 public static void main(String[] args) {
  new MyCalculator().go();
 }
 /**
 *采用成员内部类方式,实现监听器接口,方便访问主类内类内部成员。
 *此类负责数字按钮Action事件监听和处理
 */
 class NumberListener implements ActionListener{
  public void actionPerformed(ActionEvent e){
   if (!append) {
    tf.setText("");
    append=true;
   }
   String s=tf.getText();
   s+=e.getActionCommand();
   tf.setText(s);
   if (!btn[10].isEnabled()){
    for(int i=10;i<=14;i++) btn[i].setEnabled(true);
   }
  }
 }
 /**
 * 成员内部类,负责操作符按钮的事件处理
 */
 class OperatorListener implements ActionListener{
  public void actionPerformed(ActionEvent e){
   if (!append) return;
   for(int i=10;i<=14;i++) btn[i].setEnabled(false);
   String s=tf.getText();
   long num=Long.parseLong(s);//get the number of textfield
   append=false; //set append
   switch(operator){
    case &#39;+&#39;:result+=num;break;
    case &#39;-&#39;:result-=num;break;
    case &#39;*&#39;:result*=num;break;
    case &#39;/&#39;:{
     if (num==0) result=0;
     else result/=num;
     break;
    }
    case &#39;=&#39;:result=num;break;
   }
   tf.setText(String.valueOf(result));
   //set the value of result to textfield
   String op=e.getActionCommand();
   operator=op.charAt(0); // set operator
  }
 }
}

Method three:

package wanwa;
import java.util.*;
public class calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("*****************简易计算器****************");
System.out.println("*\t\t\t\t\t*");
System.out.println("* 使用说明: 1.加法 2.减法 3.乘法 4.除法 *");
System.out.println("*\t\t\t\t\t*");
System.out.println("*****************************************");
for(int i=0;i<100;i++){
System.out.print("\n请选择运算规则:");
int num = input.nextInt();
switch(num){
case 1:
System.out.println("\n******你选择了加法******\n");
System.out.print("请输入第1个加数:");
int jiashu1 = input.nextInt();
System.out.print("请输入第2个加数:");
int jiashu2 = input.nextInt();
System.out.println("运算结果为:" + jiashu1 + " + " + jiashu1 + " = " + (jiashu1 + jiashu2));
break;
case 2:
System.out.println("\n******你选择了减法******\n");
System.out.print("请输入被减数:");
int jianshu1 = input.nextInt();
System.out.print("请输入减数:");
int jianshu2 = input.nextInt();
System.out.println("运算结果为:" + jianshu1 + " - " + jianshu2 + " = " + (jianshu1 - jianshu2));
break;
case 3:
System.out.println("\n******你选择了乘法******\n");
System.out.print("请输入第1个因数:");
int chengfa1 = input.nextInt();
System.out.print("请输入第2个因数:");
int chengfa2 = input.nextInt();
System.out.println("运算结果为:" + chengfa1 + " * " + chengfa2 + " = " + (chengfa1 * chengfa2));
break;
case 4:
System.out.println("\n******你选择了除法******\n");
System.out.print("请输入被除数:");
double chufa1 = input.nextInt();
System.out.print("请输入除数:");
double chufa2 = input.nextInt();
System.out.println("运算结果为:" + chufa1 + " / " + chufa2 + " = " + (chufa1 / chufa2) + " 余 " + (chufa1 % chufa2));
break;
default:
System.out.println("\n你的选择有错,请重新选择!");
break;
}
}
}
}

Method four:

package wanwa;
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);
}
}

I hope this article will be helpful to everyone in Java programming.

For more examples and summary of common methods of writing calculators in Java, please pay attention to the PHP Chinese website for related articles!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to distinguish between business logic and storage logic in back-end development?How to distinguish between business logic and storage logic in back-end development?Apr 19, 2025 pm 09:18 PM

How to distinguish between business logic and storage logic in the three-layer architecture of back-end development? In back-end development, common three-tier architectures include controller, service and...

When the front-end passes data to the back-end, the back-end displays that the obtained data is NULL. How to solve it?When the front-end passes data to the back-end, the back-end displays that the obtained data is NULL. How to solve it?Apr 19, 2025 pm 09:15 PM

Problem description: During the development process using Ruoyi separate version, when the front-end passes data to the back-end, the back-end displays that the obtained data is NULL. The following are...

How to use CompletableFuture to ensure the order of batch interface requests and efficiently process the results?How to use CompletableFuture to ensure the order of batch interface requests and efficiently process the results?Apr 19, 2025 pm 09:09 PM

Efficient processing of batch interface requests: Using CompletableFuture to ensure order When processing large amounts of data, concurrent calls to third-party interfaces can significantly improve efficiency...

Java虚拟线程与线程池:为什么在虚拟线程池中复用虚拟线程会失败?Java虚拟线程与线程池:为什么在虚拟线程池中复用虚拟线程会失败?Apr 19, 2025 pm 09:06 PM

深入探讨Java虚拟线程与线程池的协同工作本文将分析Java虚拟线程在使用Executors.newVirtualThreadPerTaskExecutor()创建的...

In MyBatis, what type should be used when comparing Java types with MySQL's datetime types?In MyBatis, what type should be used when comparing Java types with MySQL's datetime types?Apr 19, 2025 pm 09:03 PM

In MyBatis, how to compare Java types with MySQL's datetime types is a problem that many developers often encounter when doing database operations. ...

How to elegantly turn asynchronous operations into synchronous operations in Java?How to elegantly turn asynchronous operations into synchronous operations in Java?Apr 19, 2025 pm 09:00 PM

The elegant implementation of Java asynchronous to synchronization In Java development, you often encounter scenarios where asynchronous operations need to be converted into synchronous operations. Recently, a developer mentioned...

In a Java single-threaded environment, will instruction reordering lead to a change in the code output order?In a Java single-threaded environment, will instruction reordering lead to a change in the code output order?Apr 19, 2025 pm 08:57 PM

An interesting and often discussed topic in Java programming is instruction reordering and its impact on program execution. The question we are going to discuss today is that Java...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function