Do calculation in java

Mathematical calculations in Java

In mathematics, an operation is an action where one or more operands with the help of an operator leads to a solution. The operator can be one of the counters and operands can be represented by, for example, a number.

How to do mathematical calculations in Java?

When solving technical problems, it is common to have to do several numerical calculations. Initiating a calculation in Java is very easy, and Java also provides the standard class java.lang.Math contains several common mathematical calculations — for example, the square root and trigonometric functions.

Initiating a calculation in Java is easy as the most common calculation methods are available by default in Java.

Below are some of the most common math operations in Java that you should be familiar with.

Calculation Notation Data type resultat Ex. int A = 10, int B = 4
Addition + int A + B = 14.0
Subtraction int A – B = 6
Multiplikation * int A * B = 40
Division / double A / B = 2.5
Modulus % double A % B = 2.0
Less than boolean A < B = false
Greater than > boolean A > B = true
Less than or equal to boolean A
Greater than or equal to >= boolean A >= B = true
Equal to == boolean A == B = false
Not equal to != boolean A != B = true

Examples of Mathematical Calculations in Java

Let’s have a look at some math calculations in Java. We recognize the mathematical operations, and they are hopefully nothing new. However, it is important to be careful what data type you declare to a variable. Consider the following code:

public class mathematical_calculations < public static void main(String[] args) < // Variables of type double double A = 10; double B = 4; System.out.println(A+B); System.out.println(A-B); System.out.println(A*B); System.out.println(A/B); >>

Which is the result we expect from each mathematical operation. However, if A, and B instead are integers, we get the following results:

public class matematiska_operationer < public static void main(String[] args) < // Variables of data type Integer int A = 10; int B = 4; System.out.println(A+B); System.out.println(A-B); System.out.println(A*B); System.out.println(A/B); >>

That is, a mathematical operation with a particular data type will result in a result of the same data type. For example, a division with 10/4 (which normally becomes 2.5), instead becomes 2, since a division of two integers will result in an integer type result – the decimal sign will, therefore, left out.

A mathematical operation with a certain data type will lead to a result of the same data type.

Can you perform a mathematical operation with different data types in Java?

Absolutely! If we look at the same example again, but with different data types:

public class matematiska_operationer < public static void main(String[] args) < // Variables of different data types int A = 10; double B = 4; System.out.println(A+B); System.out.println(A-B); System.out.println(A*B); System.out.println(A/B); >>

Which is the same result we got in the case when both variables were of the data type double. Furthermore, Java has the priority order that a mathematical operation that contains a floating-point will result in a floating-point. Since we performed mathematical operations with both integers and floating-point (double), Java will prioritize the floating-point, so the result is a double.

Modulo Operations in Java

The operation that is usually a little tricky to understand at first is Modulo, it returns the remainder at the division. Let’s take an example to show Modulus calculations. Say you have a cinnamon bun that is 21 cm long (yes, it’s a long cinnamon bun). You want to divide it into precisely 6 cm long pieces (critical that they are exactly 6 cm). You can then split the cinnamon bun length into three pieces, and we then have 3 cm left of the cake, the 3 cm is our leftover. Additionally, below are some more examples of calculations

int x = 7; int y = 2; int mod = x % y; // mod then becomes the rest when we divide 7 by 2 -> mod = 1 int x = 8; int Y = 4; int mod = x % y; // Here we get mod = 0, because we get no remainder when we divide 8 by 4 int x = 9; int y = 5; int mod = x % y; // The remainder becomes -> mod = 4

Equality and Relational Operators in Java

We use the so-called Equality and Relational operations to determine if a value is greater, smaller or equal to another value. Let’s take the same example again:

public class mathematical_operations < public static void main(String[] args) < // Variables of different data types int A = 10; int B = 4; System.out.println(A >B); // Is A greater than B? System.out.println(A < B); // Is A smaller than B? System.out.println(A = B); // Is A bigger or equal to B? System.out.println(A == B); // Is A exactly the same value as B? > >

The result in this case are

true false false true false

That is, if the operation is true, the result is true, and if the operation is false, the result is false. The data type that results is therefore of the boolean type. Moreover, we will have a look at the conditional operators a few pages ahead.

Источник

Calculator in Java

Calculator in Java

Calculator in Java is used to calculate addition, subtraction, multiplication, division, modulus, power of numbers, etc. We can do this calculator operation using a plain Java switch case and using Java swing standalone application. In Plain Java calculator operation, we don’t need any extra libraries, but we must require java.awt.event in the case of swing application.*, javax.swing.*, java.awt.*packages.

Methods

Swing methods for the calculator:

  • add(Component component): It is used to add the component to the container.
  • setSize(int x, int y): It is used to set the size of the container as per given dimensions.
  • setText(String string): It is used to set the string text.
  • getText(): It is used to get the text of the container.
  • addActionListenerListener(ActionListener actionListener): It is used to set the action to the container.
  • setBackground(Color color) : It is used to set the background color.

How to Create a Calculator in Java?

We can create a calculator in 2 ways:

1. Using the Switch Case Statement

Step 1: User enters the character for which operation wants to perform like “+”, “-”, “*”, “/”, “%”, “^” etc.

Step 2: Within the switch case, we have implemented logic for each character.

Step 3: Based on character operation performed like addition, subtraction, multiplication, division, modulus (finds remainder) and power of the number.

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 >
Example #1 – Switch Case Calculator Functionality
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 for addition and subtraction

for addition and subtraction - 1

o/p for multiplication and division

for multiplication and division - 2

o/p for remainder and power

for remainder and power - 3

2. Using Swing Graphics

Step1: Create a class and extends it from JFrame, ActionerListener.

Step2: Creating buttons for numbers from 0-9 and character buttons like +, -, *, *, % etc.

Step3: Write an Action listener for all the buttons.

Step4: Add all these components to the Screen.

Example 2 – Swing Calculator
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) 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); > > > 

Calculator in Java Example 1

Calculator in Java Example 2

Calculator in Java Example 3

Conclusion

Java Calculator is used to calculating operations like addition, subtraction, division, multiplication, modulus, and power. This can be done in 2 ways by using a switch case statement and by using swing API.

This is a guide to Calculator in Java. Here we discuss the Introduction to Calculator in Java and its different Methods and Examples and Code Implementation. You can also go through our other suggested articles to learn more –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8

Источник

Читайте также:  Jquery this css attribute
Оцените статью