首页 > Java > java教程 > 正文

Java 计算器

王林
发布: 2024-08-30 15:40:49
原创
664 人浏览过

Java 中的计算器用于计算加法、减法、乘法、除法、模数、数字幂等。我们可以使用普通的 Java switch case 和 Java swing 独立应用程序来执行此计算器操作。在Plain Java计算器操作中,我们不需要任何额外的库,但在swing应用程序的情况下,我们必须需要java.awt.event.*,javax.swing.*,java.awt.*packages。

广告 该类别中的热门课程 JAVA 掌握 - 专业化 | 78 课程系列 | 15 次模拟测试

方法

计算器的摆动方法:

  • add(Component 组件): 用于将组件添加到容器中。
  • setSize(int x, int y): 用于根据给定尺寸设置容器的大小。
  • setText(String string): 用于设置字符串文本。
  • getText():用于获取容器的文本。
  • addActionListenerListener(ActionListener actionListener): 用于给容器设置action。
  • setBackground(Color color) : 用于设置背景颜色。

如何用 Java 创建计算器?

我们可以通过两种方式创建计算器:

  • 使用 Switch Case 语句。
  • 使用 Swing 图形。

1.使用 Switch Case 语句

第1步:用户输入要执行操作的字符“+”、“-”、“*”、“/”、“%”、“^”等等

第 2 步:在 switch case 中,我们为每个角色实现了逻辑。

第 3 步:基于执行的字符运算,如加法、减法、乘法、除法、模数(求余数)和数字的幂。

语法:

public class CalculatorSwitchCase
{
//Ask input from user
switch(character)
{
case '+'://addition operation
case '-'://subtraction operation
case '*'://multiplication operation
case '/'://division operation
case '%'://modulus operation
case '^'://power operation
}
//display output
}
登录后复制
示例 #1 – Switch Case 计算器功能

代码:

package com.calculator;

import java.util.Scanner;

public class CalculatorSwitchCase {
	public static void main(String[] args) {

		// declaring varibales
		double firstNumber, secondNumber;
		double result_operation_output;
		// Creating scanner for object for allow input
		Scanner scannerObject = new Scanner(System.in);
		do {
			System.out.println("==============================================");
			System.out.println("1. + for ADDITION");
			System.out.println("2. - for SUBTRACTION");
			System.out.println("3. * for MULTIPLICATION");
			System.out.println("5. 4. / for DIVISION");
			System.out.println("6. % for REMAINDER");
			System.out.println("7. ^ for POWER");
			System.out.println("8. Q for QUIT");
			System.out.println("==============================================");

			// ask the user to enter first number
			System.out.print("Enter your first number:\n");
			firstNumber = scannerObject.nextDouble();
			// ask the user to enter second number
			System.out.print("Enter your second number:\n");
			secondNumber = scannerObject.nextDouble();

			System.out.print("Enter an operators like (+, -, *, /, %, ^) only:\n ");
			// storing the operator in char object
			char operator = scannerObject.next().charAt(0);

			switch (operator) {
			case '+':
				result_operation_output = firstNumber + secondNumber;
				break;

			case '-':
				result_operation_output = firstNumber - secondNumber;
				break;

			case '*':
				result_operation_output = firstNumber * secondNumber;
				break;

			case '/':
				result_operation_output = firstNumber / secondNumber;
				break;

			case '%':
				result_operation_output = firstNumber % secondNumber;
				break;

			case '^':
				result_operation_output = Math.pow(firstNumber, secondNumber);
				break;

			case 'Q':
				System.exit(0);

			default:
				System.out.printf("Please enter specified operator only");
				return;
			}
			System.out.println(firstNumber + " " + operator + " " + secondNumber + " is : " + result_operation_output);
		} while (result_operation_output != 'Q');
		scannerObject.close();
	}
}
登录后复制

输出:

o/p 用于加法和减法

Java 计算器

o/p 用于乘法和除法

Java 计算器

余数和幂的o/p

Java 计算器

2.使用 Swing 图形

Step1:创建一个类并从 JFrame、ActionerListener 扩展它。

第 2 步:创建 0-9 的数字按钮和 +、-、*、*、% 等字符按钮

第三步:为所有按钮编写一个 Action 监听器。

第四步:将所有这些组件添加到屏幕上。

示例 2 – 摆动计算器

代码:

package com.calculator.swing;
//Java program to create a simple calculator 

//with basic +, -, /, * using java swing elements 

import java.awt.Color;
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;
import javax.swing.UIManager;

@SuppressWarnings("serial")
public class CalculatorSwing extends JFrame implements ActionListener {
	// create a frame
	static JFrame frameToDisplay;

	// create a textfield
	static JTextField labeTextField;

	// it store the operands and operators
	String string0, string1, string2;

	// constructor
	CalculatorSwing() {
		string0 = string1 = string2 = "";
	}

	// main function to java application
	public static void main(String args[]) {
		// create the frame to display the screen
		frameToDisplay = new JFrame("My Calculator");

		try {
			// used to set the look and feel for the application
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception exception) {
			System.err.println(exception.getMessage());
		}

		// create the class object
		CalculatorSwing calculatorSwing = new CalculatorSwing();

		// create text field
		labeTextField = new JTextField(16);

		// set to the non editable
		labeTextField.setEditable(false);

		// declaring numbers buttons and operators buttons
		JButton button_0, button_1, button_2, button_3, button_4, button_5, button_6, button_7, button_8, button_9,
				button_add, button_subtract, button_div, button_mul, button_dot, button_equal1, button_equal2;
		// creating numbers buttons
		button_0 = new JButton("0");
		button_1 = new JButton("1");
		button_2 = new JButton("2");
		button_3 = new JButton("3");
		button_4 = new JButton("4");
		button_5 = new JButton("5");
		button_6 = new JButton("6");
		button_7 = new JButton("7");
		button_8 = new JButton("8");
		button_9 = new JButton("9");
		// creating equals buttons
		button_equal2 = new JButton("=");
		// creating operators like +,-,*,/ buttons
		button_add = new JButton("+");
		button_subtract = new JButton("-");
		button_div = new JButton("/");
		button_mul = new JButton("*");
		button_equal1 = new JButton("C");
		// creating dot(.) buttons
		button_dot = new JButton(".");
		// creating panel
		JPanel jPanel = new JPanel();
		// adding action listeners to the buttons
		button_mul.addActionListener(calculatorSwing);
		button_div.addActionListener(calculatorSwing);
		button_subtract.addActionListener(calculatorSwing);
		button_add.addActionListener(calculatorSwing);
		button_9.addActionListener(calculatorSwing);
		button_8.addActionListener(calculatorSwing);
		button_7.addActionListener(calculatorSwing);
		button_6.addActionListener(calculatorSwing);
		button_5.addActionListener(calculatorSwing);
		button_4.addActionListener(calculatorSwing);
		button_3.addActionListener(calculatorSwing);
		button_2.addActionListener(calculatorSwing);
		button_1.addActionListener(calculatorSwing);
		button_0.addActionListener(calculatorSwing);
		button_dot.addActionListener(calculatorSwing);
		button_equal1.addActionListener(calculatorSwing);
		button_equal2.addActionListener(calculatorSwing);
		// add all elements to the panel
		jPanel.add(labeTextField);
		jPanel.add(button_add);
		jPanel.add(button_1);
		jPanel.add(button_2);
		jPanel.add(button_3);
		jPanel.add(button_subtract);
		jPanel.add(button_4);
		jPanel.add(button_5);
		jPanel.add(button_6);
		jPanel.add(button_mul);
		jPanel.add(button_7);
		jPanel.add(button_8);
		jPanel.add(button_9);
		jPanel.add(button_div);
		jPanel.add(button_dot);
		jPanel.add(button_0);
		jPanel.add(button_equal1);
		jPanel.add(button_equal2);
		// set background of the panel
		jPanel.setBackground(Color.darkGray);
		// add the panel to the frame
		frameToDisplay.add(jPanel);
		frameToDisplay.setSize(210, 230);
		frameToDisplay.show();
	}
	//action listener implementation
	public void actionPerformed(ActionEvent e) {
		String input = e.getActionCommand();
		// check if the given  value is number
		if ((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == '.') {
			// if operand is present then add to second no
			if (!string1.equals(""))
				string2 = string2 + input;
			else
				string0 = string0 + input;
			// set the value to the text
			labeTextField.setText(string0 + string1 + string2);
		} else if (input.charAt(0) == 'C') {
			// clearing
			string0 = string1 = string2 = "";
			// set the value of the text
			labeTextField.setText(string0 + string1 + string2);
		} else if (input.charAt(0) == '=') {
			double equalsInput;
			// store the value in the first index
			if (string1.equals("+"))
				equalsInput = (Double.parseDouble(string0) + Double.parseDouble(string2));
			else if (string1.equals("-"))
				equalsInput = (Double.parseDouble(string0) - Double.parseDouble(string2));
			else if (string1.equals("/"))
				equalsInput = (Double.parseDouble(string0) / Double.parseDouble(string2));
			else
				equalsInput = (Double.parseDouble(string0) * Double.parseDouble(string2));
			// set the value of the text
			labeTextField.setText(string0 + string1 + string2 + "=" + equalsInput);
			// converting int to string
			string0 = Double.toString(equalsInput);
			string1 = string2 = "";
		} else {
			// if no operand is there
			if (string1.equals("") || string2.equals(""))
				string1 = input;
			else {
				double te;
				// store the value in the first index
				if (string1.equals("+"))
					te = (Double.parseDouble(string0) + Double.parseDouble(string2));
				else if (string1.equals("-"))
					te = (Double.parseDouble(string0) - Double.parseDouble(string2));
				else if (string1.equals("/"))
					te = (Double.parseDouble(string0) / Double.parseDouble(string2));
				else
					te = (Double.parseDouble(string0) * Double.parseDouble(string2));
				// converting int to string
				string0 = Double.toString(te);
				// put the operator
				string1 = input;
				// take the operand as blank
				string2 = "";
			}
			// set the value of the text
			labeTextField.setText(string0 + string1 + string2);
		}
	}
}
登录后复制

输出:

Java 计算器

Java 计算器

Java 计算器

结论

Java计算器用于计算加、减、除、乘、模和幂等运算。这可以通过使用 switch case 语句和使用 swing API 两种方式来完成。

以上是Java 计算器的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板