ホームページ  >  記事  >  Java  >  Javaの電卓

Javaの電卓

王林
王林オリジナル
2024-08-30 15:40:49602ブラウズ

Java の電卓は、加算、減算、乗算、除算、法、数値のべき乗などを計算するために使用されます。この電卓操作は、プレーンな Java スイッチ ケースと Java Swing スタンドアロン アプリケーションを使用して実行できます。 Plain Java 電卓の操作では追加のライブラリは必要ありませんが、swing application.*、javax.swing.*、java.awt.*packages.

の場合は java.awt.event が必要です。 広告 このカテゴリーの人気コース JAVA マスタリー - スペシャライゼーション | 78 コース シリーズ | 15 回の模擬テスト

メソッド

電卓のスイング方法:

  • add(Component コンポーネント): コンポーネントをコンテナーに追加するために使用されます。
  • setSize(int x, int y): 指定された寸法に従ってコンテナーのサイズを設定するために使用されます。
  • setText(String string): 文字列テキストを設定するために使用されます。
  • getText(): コンテナのテキストを取得するために使用されます。
  • addActionListenerListener(ActionListener actionListener): コンテナにアクションを設定するために使用されます。
  • setBackground(Color color) : 背景色の設定に使用されます。

Java で電卓を作成するには?

電卓は 2 つの方法で作成できます:

  • Switch Case ステートメントの使用。
  • Swing グラフィックを使用します。

1. Switch Case ステートメントの使用

ステップ 1: ユーザーは操作を実行したい文字を入力します。 「+」、「-」、「*」、「/」、「%」、「^」など

ステップ 2: switch ケース内に、各キャラクターのロジックを実装しました。

ステップ 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 – スイッチケース計算機能

コード:

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.スインググラフィックの使用

ステップ 1: クラスを作成し、JFrame、ActionerListener から拡張します。

ステップ 2: 0 ~ 9 の数字ボタンと +、-、*、*、% などの文字ボタンを作成します。

ステップ 3: すべてのボタンのアクション リスナーを作成します。

ステップ 4: これらすべてのコンポーネントを画面に追加します。

例 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 Calculator は、加算、減算、除算、乗算、剰余、べき乗などの演算の計算に使用されます。これは、switch case ステートメントを使用する方法と、swing API を使用する方法の 2 つの方法で実行できます。

以上がJavaの電卓の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:Java辞書次の記事:Java辞書