How To Create A Calculator In Javafx
Introduction to 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 of Calculator in Java
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:
- Using the Switch Case Statement.
- Using Swing graphics.
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.
Syntax:
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
Code:
//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();
}
}
Output:
o/p for addition and subtraction
o/p for multiplication and division
o/p for remainder and power
2. Using Swing Graphics
Step1: Creating 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
Code:
//package com.calculator.swing;
//Javaprogramtocreateasimplecalculator
//withbasic+,-,/,*usingjavaswingelements
importjava.awt.Color;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.UIManager;
@SuppressWarnings("serial")
publicclassCalculatorSwingextendsJFrameimplementsActionListener{
//createaframe
staticJFrameframeToDisplay;
//createatextfield
staticJTextFieldlabeTextField;
//itstoretheoperandsandoperators
Stringstring0,string1,string2;
//constructor
CalculatorSwing(){
string0=string1=string2="";
}
//mainfunctiontojavaapplication
publicstaticvoidmain(Stringargs[]){
//createtheframetodisplaythescreen
frameToDisplay=newJFrame("MyCalculator");
try{
//usedtosetthelookandfeelfortheapplication
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exceptionexception){
System.err.println(exception.getMessage());
}
//createtheclassobject
CalculatorSwingcalculatorSwing=newCalculatorSwing();
//createtextfield
labeTextField=newJTextField(16);
//settothenoneditable
labeTextField.setEditable(false);
//declaringnumbersbuttonsandoperatorsbuttons
JButtonbutton_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;
//creatingnumbersbuttons
button_0=newJButton("0");
button_1=newJButton("1");
button_2=newJButton("2");
button_3=newJButton("3");
button_4=newJButton("4");
button_5=newJButton("5");
button_6=newJButton("6");
button_7=newJButton("7");
button_8=newJButton("8");
button_9=newJButton("9");
//creatingequalsbuttons
button_equal2=newJButton("=");
//creatingoperatorslike+,-,*,/buttons
button_add=newJButton("+");
button_subtract=newJButton("-");
button_div=newJButton("/");
button_mul=newJButton("*");
button_equal1=newJButton("C");
//creatingdot(.)buttons
button_dot=newJButton(".");
//creatingpanel
JPaneljPanel=newJPanel();
//addingactionlistenerstothebuttons
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);
//addallelementstothepanel
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);
//setbackgroundofthepanel
jPanel.setBackground(Color.darkGray);
//addthepaneltotheframe
frameToDisplay.add(jPanel);
frameToDisplay.setSize(210,230);
frameToDisplay.show();
}
//actionlistenerimplementation
publicvoidactionPerformed(ActionEvente){
Stringinput=e.getActionCommand();
//checkifthegiven valueisnumber
if((input.charAt(0)>='0'&&input.charAt(0)<='9')||input.charAt(0)=='.'){
//ifoperandispresentthenaddtosecondno
if(!string1.equals(""))
string2=string2+input;
else
string0=string0+input;
//setthevaluetothetext
labeTextField.setText(string0+string1+string2);
}elseif(input.charAt(0)=='C'){
//clearing
string0=string1=string2="";
//setthevalueofthetext
labeTextField.setText(string0+string1+string2);
}elseif(input.charAt(0)=='='){
doubleequalsInput;
//storethevalueinthefirstindex
if(string1.equals("+"))
equalsInput=(Double.parseDouble(string0)+Double.parseDouble(string2));
elseif(string1.equals("-"))
equalsInput=(Double.parseDouble(string0)-Double.parseDouble(string2));
elseif(string1.equals("/"))
equalsInput=(Double.parseDouble(string0)/Double.parseDouble(string2));
else
equalsInput=(Double.parseDouble(string0)*Double.parseDouble(string2));
//setthevalueofthetext
labeTextField.setText(string0+string1+string2+"="+equalsInput);
//convertinginttostring
string0=Double.toString(equalsInput);
string1=string2="";
}else{
//ifnooperandisthere
if(string1.equals("")||string2.equals(""))
string1=input;
else{
doublete;
//storethevalueinthefirstindex
if(string1.equals("+"))
te=(Double.parseDouble(string0)+Double.parseDouble(string2));
elseif(string1.equals("-"))
te=(Double.parseDouble(string0)-Double.parseDouble(string2));
elseif(string1.equals("/"))
te=(Double.parseDouble(string0)/Double.parseDouble(string2));
else
te=(Double.parseDouble(string0)*Double.parseDouble(string2));
//convertinginttostring
string0=Double.toString(te);
//puttheoperator
string1=input;
//taketheoperandasblank
string2="";
}
//setthevalueofthetext
labeTextField.setText(string0+string1+string2);
}
}
}
Output:
Conclusion
Java Calculator is used to calculating operations like addition, subtraction, division, multiplication, modulus, and power. This calculator in Java can be done in 2 ways by using a switch case statement and by using swing API.
Recommended Articles
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 –
- Java 8 Collectors With Characteristics
- How Does Object Class Works in Java?
- Java Directories (Examples)
- Introduction to repaint in Java
How To Create A Calculator In Javafx
Source: https://www.educba.com/calculator-in-java/
Posted by: gomezclot1989.blogspot.com
0 Response to "How To Create A Calculator In Javafx"
Post a Comment