Double calculator in java

Java Guides

In this tutorial, we’ll implement a very simple calculator in Java supporting addition, subtraction, multiplication, and division operations.

We’ll also take the operator and operands as inputs and process the calculations based on them.

This tutorial is useful for beginners to understand how to build a very simple calculator using Core Java.

We will use the Scanner class to read user inputs such as operator, number 1, and number 2.

We will make a simple calculator using if-else as well as switch-case statement:

Simple calculator using if-else in Java

package com.java.calculator; import java.util.InputMismatchException; import java.util.Scanner; public class BasicCalculatorIfElse < public static void main(String[] args) < System.out.println("---------------------------------- \n" + "Welcome to Basic Calculator \n" + "----------------------------------"); System.out.println("Following operations are supported : \n" + "1. Addition (+) \n" + "2. Subtraction (-) \n" + "3. Multiplication (* OR x) \n" + "4. Division (/) \n"); try(Scanner scanner = new Scanner(System.in)) < System.out.println("Enter an operator: (+ OR - OR * OR /) "); char operation = scanner.next().charAt(0); if (!(operation == '+' || operation == '-' || operation == '*' || operation == 'x' || operation == '/')) < System.err.println("Invalid Operator. Please use only + or - or * or /"); >System.out.println("Enter First Number: "); double num1 = scanner.nextDouble(); System.out.println("Enter Second Number: "); double num2 = scanner.nextDouble(); if (operation == '/' && num2 == 0.0) < System.err.println("Second Number cannot be zero for Division operation."); >if (operation == '+') < System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); >else if (operation == '-') < System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); >else if (operation == '*' || operation == 'x') < System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); >else if (operation == '/') < System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); >else < System.err.println("Invalid Operator Specified."); >> catch (InputMismatchException exc) < System.err.println(exc.getMessage()); >> > 

Output :

---------------------------------- Welcome to Basic Calculator ---------------------------------- Following operations are supported : 1. Addition (+) 2. Subtraction (-) 3. Multiplication (* OR x) 4. Division (/) Enter an operator: (+ OR - OR * OR /) + Enter First Number: 10 Enter Second Number: 20 10.0 + 20.0 = 30.0

Simple calculator using switch case in Java

package com.java.calculator; import java.util.InputMismatchException; import java.util.Scanner; public class BasicCalculator < public static void main(String[] args) < System.out.println("---------------------------------- \n" + "Welcome to Basic Calculator \n" + "----------------------------------"); System.out.println("Following operations are supported : \n" + "1. Addition (+) \n" + "2. Subtraction (-) \n" + "3. Multiplication (* OR x) \n" + "4. Division (/) \n"); try (Scanner scanner = new Scanner(System.in)) < System.out.println("Enter an operator (+, -, *, /):"); char operation = scanner.next().charAt(0); if (!(operation == '+' || operation == '-' || operation == '*' || operation == 'x' || operation == '/')) < System.err.println("Invalid Operator. Please use only + or - or * or /"); >System.out.println("Enter First Number: "); double num1 = scanner.nextDouble(); System.out.println("Enter Second Number: "); double num2 = scanner.nextDouble(); if (operation == '/' && num2 == 0.0) < System.err.println("Second Number cannot be zero for Division operation."); >switch (operation) < case '+': System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); break; case '-': System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); break; case '*': System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); break; case 'x': System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); break; case '/': System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); break; default: System.err.println("Invalid Operator Specified."); break; >> catch (InputMismatchException exc) < System.err.println(exc.getMessage()); >> > 

Output :

---------------------------------- Welcome to Basic Calculator ---------------------------------- Following operations are supported : 1. Addition (+) 2. Subtraction (-) 3. Multiplication (* OR x) 4. Division (/) Enter an operator (+, -, *, /): - Enter First Number: 20 Enter Second Number: 10 20.0 - 10.0 = 10.0

Источник

Читайте также:  Absolute path linking in html

Java Calculator using Swing Example

Swing is a GUI widget toolkit for Java. It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way. So lets see how to create a calculator in java.

1. Introduction

  • A single API is to be sufficient to support multiple look and feel.
  • API is to model driven so that highest level API is not required to have the data.
  • API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers to use it.

2. JAVA Swing

Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton , JTextField , JTextArea , JRadioButton , JCheckbox , JMenu , JColorChooser etc.

2.1 MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

  • A Model represents component’s data.
  • View represents visual representation of the component’s data.
  • Controller takes the input from the user on the view and reflects the changes in Component’s data.
  • Swing component have Model as a separate element and View and Controller part are clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.

Every user interface considers the following three main aspects:

  • UI elements : These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex.
  • Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface).
  • Behavior: These are events which occur when the user interacts with UI elements.

2.2 Swing Features

  • Light Weight – Swing component are independent of native Operating System’s API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.
  • Rich controls – Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls.
  • Highly Customizable – Swing controls can be customized in very easy way as visual apperance is independent of internal representation.
  • Pluggable look-and-feel– SWING based GUI Application look and feel can be changed at run time based on available values.

2.3 Setup

Popular Java Editors:
To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:

  • Notepad: On Windows machine you can use any simple text editor like Notepad TextPad.
  • NetBeans: is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
  • Eclipse: is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org

2.4 Class and description

  • Component: A Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation.
  • Container: A Container is a component that can contain other SWING components.
  • JComponent: A JComponent is a base class for all swing UI components. In order to use a swing component that inherits from JComponent, component must be in a containment hierarchy whose root is a top-level Swing container.
Читайте также:  Use java util logging

3. Swing Java Calculator Example

This tutorial is about how to make a calculator in Java. Below I have shared the simple calculator program in java using swing. It is a simple calculator in Java which can perform basic arithmetic operations.

import java.awt.*; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JTextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Calculator extends JFrame implements ActionListener < JButton addButton,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,BACKSPACE,CE,C,MC,div,sqrt,MR,mul,per,MS,sub,prop,M,pm,dot,eq; JTextField mainTextField, memoryTextField; double result=0,memory=0,n1=0; //Mark the first number for easy calculation int first=1; //First number for percentage calculation double num; //Flag for appending digits or starting a new number /*1->Appending a digit to the existing number 2->Taking a new number as input*/ int opt=2; //Flag to mark binary operation for '=' button /*0->No Operation 1->Addtion 2->Subtraction 3->Division 4->Multiplication*/ int oper1=0,oper2=0; Calculator() < setTitle("Calculator"); setSize(300,300); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); initComponents(); >//Function for creating User Interface void initComponents() < mainTextField = new JTextField(32); mainTextField.setText("0"); add(mainTextField,BorderLayout.NORTH); mainTextField.setHorizontalAlignment(JTextField.RIGHT); JPanel panel7 = new JPanel(); //Panel 1 JPanel panel1 = new JPanel(); memoryTextField = new JTextField(5); memoryTextField.setText(" "); panel1.add(memoryTextField); MC = new JButton("MC"); MC.setForeground(Color.BLACK); panel1.add(MC); MR = new JButton("MR"); MR.setForeground(Color.BLACK); panel1.add(MR); M = new JButton("M+"); M.setForeground(Color.BLACK); panel1.add(M); MS = new JButton("MS"); MS.setForeground(Color.BLACK); panel1.add(MS); panel7.add(panel1); //Panel 2 JPanel panel2 = new JPanel(); CE= new JButton("CE"); CE.setForeground(Color.BLACK); panel2.add(CE); C = new JButton("C"); panel2.add(C); C.setForeground(Color.BLACK); BACKSPACE = new JButton("BACKSPACE"); BACKSPACE.setForeground(Color.BLACK); panel2.add(BACKSPACE); sqrt = new JButton("sqrt"); sqrt.setForeground(Color.BLUE); panel2.add(sqrt); panel7.add(panel2); //Panel 3 JPanel panel3 = new JPanel(); b7 = new JButton("7"); b7.setForeground(Color.BLUE); panel3.add(b7); b8= new JButton("8"); b8.setForeground(Color.BLUE); panel3.add(b8); b9 = new JButton("9"); b9.setForeground(Color.BLUE); panel3.add(b9); div = new JButton("/"); div.setForeground(Color.BLACK); panel3.add(div); per = new JButton("%"); per.setForeground(Color.BLUE); panel3.add(per); panel7.add(panel3); //Panel 4 JPanel panel4 = new JPanel(); b4= new JButton("4"); b4.setForeground(Color.BLUE); panel4.add(b4); b5 = new JButton("5"); b5.setForeground(Color.BLUE); panel4.add(b5); b6= new JButton("6"); b6.setForeground(Color.BLUE); panel4.add(b6); mul = new JButton("*"); mul.setForeground(Color.BLACK); panel4.add(mul); prop = new JButton("1/x"); prop.setForeground(Color.BLUE); panel4.add(prop); panel7.add(panel4); //Panel 5 JPanel panel5 = new JPanel(); b1 = new JButton("1"); b1.setForeground(Color.BLUE); panel5.add(b1); b2= new JButton("2"); b2.setForeground(Color.BLUE); panel5.add(b2); b3 = new JButton("3"); b3.setForeground(Color.BLUE); panel5.add(b3); sub = new JButton("-"); sub.setForeground(Color.BLACK); panel5.add(sub); pm= new JButton("+/-"); pm.setForeground(Color.BLUE); panel5.add(pm); panel7.add(panel5); //Panel 6 JPanel panel6 = new JPanel(); b0= new JButton("0"); b0.setForeground(Color.BLUE); panel6.add(b0); dot= new JButton("."); dot.setForeground(Color.BLUE); panel6.add(dot); addButton = new JButton("+"); addButton.setForeground(Color.BLACK); panel6.add(addButton); eq = new JButton("="); eq.setForeground(Color.BLACK); panel6.add(eq); panel7.add(panel6); panel1.setBackground(Color.blue); panel7.setBackground(Color.LIGHT_GRAY); //Adding all individual panels to main panel7 add(panel7,BorderLayout.CENTER); //Add events addButton.addActionListener(this); b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); BACKSPACE.addActionListener(this); CE.addActionListener(this); C.addActionListener(this); MC.addActionListener(this); div.addActionListener(this); sqrt.addActionListener(this); MR.addActionListener(this); mul.addActionListener(this); per.addActionListener(this); MS.addActionListener(this); sub.addActionListener(this); prop.addActionListener(this); M.addActionListener(this); pm.addActionListener(this); dot.addActionListener(this); eq.addActionListener(this); per.addActionListener(this); >//Method when ActionListener calls its corresponding routine public void actionPerformed(ActionEvent evt) < String str; //Action Corresponding to + button if(evt.getSource()== addButton) < if(first==1) < result=num=Double.parseDouble(mainTextField.getText()); oper1=1; >else < n1=Double.parseDouble(mainTextField.getText()); oper2=1; >//Action corresponding to previous operator switch(oper1) < case 1:add1(); break; case 2:sub(); break; case 3:div(); break; case 4:mul(); break; >> //Action Corresponding to * button if(evt.getSource()==mul) < if(first==1) < result=num=Double.parseDouble(mainTextField.getText()); oper1=4; >else < n1=Double.parseDouble(mainTextField.getText()); oper2=4; >//Action corresponding to previous operator switch(oper1) < case 1:add1(); break; case 2:sub(); break; case 3:div(); break; case 4:mul(); break; >> //Action Corresponding to / button if(evt.getSource()==div) < if(first==1) < result=num=Double.parseDouble(mainTextField.getText()); oper1=3; >else < n1=Double.parseDouble(mainTextField.getText()); oper2=3; >//Action corresponding to previous operator switch(oper1) < case 1:add1(); break; case 2:sub(); break; case 3:div(); break; case 4:mul(); break; >> //Action Corresponding to - button else if(evt.getSource()==sub) < if(first==1) < result=num=Double.parseDouble(mainTextField.getText()); oper1=2; >else < n1=Double.parseDouble(mainTextField.getText()); oper2=2; >//Action corresponding to previous operator switch(oper1) < case 1:add1(); break; case 2:sub(); break; case 3:div(); break; case 4:mul(); break; >> //Action Corresponding to = button else if(evt.getSource()==eq) < double n1=Double.parseDouble(mainTextField.getText()); if(oper1==1) result=result+n1; else if(oper1==2) result=result-n1; else if(oper1==3) result=result/n1; else if(oper1==4) result=result*n1; else result=Double.parseDouble(mainTextField.getText()); num=result; str=String.valueOf(result); mainTextField.setText(str); >//Action Corresponding to MS button else if(evt.getSource()==MS) < memory=Double.parseDouble(mainTextField.getText()); str=String.valueOf("M"); memoryTextField.setText(str); >//Action Corresponding to M button else if(evt.getSource()==M) < memory=memory+Double.parseDouble(mainTextField.getText()); >//Action Corresponding to MC button else if(evt.getSource()==MC) < memory=0; mainTextField.setText("0"); memoryTextField.setText(" "); >//Action Corresponding to MR button else if(evt.getSource()==MR) < str=String.valueOf(memory); mainTextField.setText(str); >//Action Corresponding to +/- button else if(evt.getSource()==pm) < double n1=Double.parseDouble(mainTextField.getText()); n1=-n1; str=String.valueOf(n1); mainTextField.setText(str); >//Action Corresponding to 0 button else if(evt.getSource()==b0) < if(opt==1) str=String.valueOf(mainTextField.getText())+0; else str=String.valueOf(" ")+0; opt=1; mainTextField.setText(str); >//Action Corresponding to 1 button else if(evt.getSource()==b1) < if(opt==1) str=String.valueOf(mainTextField.getText())+1; else str=String.valueOf(" ")+1; opt=1; mainTextField.setText(str); >//Action Corresponding to 2 button else if(evt.getSource()==b2) < if(opt==1) str=String.valueOf(mainTextField.getText())+2; else str=String.valueOf(" ")+2; opt=1; mainTextField.setText(str); >//Action Corresponding to 3 button else if(evt.getSource()==b3) < if(opt==1) str=String.valueOf(mainTextField.getText())+3; else str=String.valueOf(" ")+3; opt=1; mainTextField.setText(str); >//Action Corresponding to 4 button else if(evt.getSource()==b4) < if(opt==1) str=String.valueOf(mainTextField.getText())+4; else str=String.valueOf(" ")+4; opt=1; mainTextField.setText(str); >//Action Corresponding to 5 button else if(evt.getSource()==b5) < if(opt==1) str=String.valueOf(mainTextField.getText())+5; else str=String.valueOf(" ")+5; opt=1; mainTextField.setText(str); >//Action Corresponding to 6 button else if(evt.getSource()==b6) < if(opt==1) str=String.valueOf(mainTextField.getText())+6; else str=String.valueOf(" ")+6; opt=1; mainTextField.setText(str); >//Action Corresponding to 7 button else if(evt.getSource()==b7) < if(opt==1) str=String.valueOf(mainTextField.getText())+7; else str=String.valueOf(" ")+7; opt=1; mainTextField.setText(str); >//Action Corresponding to 8 button else if(evt.getSource()==b8) < if(opt==1) str=String.valueOf(mainTextField.getText())+8; else str=String.valueOf(" ")+8; opt=1; mainTextField.setText(str); >//Action Corresponding to 9 button else if(evt.getSource()==b9) < if(opt==1) str=String.valueOf(mainTextField.getText())+9; else str=String.valueOf(" ")+9; opt=1; mainTextField.setText(str); >//Action Corresponding to BACKSPACE button else if(evt.getSource()==BACKSPACE) < int len; str= mainTextField.getText(); len=str.length(); if(len>=1) str=str.substring(0,len-1); mainTextField.setText(str); > //Action Corresponding to CE button else if(evt.getSource()==CE) < result=0; first=1; opt=2; str=String.valueOf('0'); mainTextField.setText(str); >//Action Corresponding to C button else if(evt.getSource()==C) < result=0; memory=0; first=1; opt=2; mainTextField.setText("0"); memoryTextField.setText(" "); >//Action Corresponding to . button else if(evt.getSource()==dot) < str=String.valueOf(mainTextField.getText())+"."; mainTextField.setText(str); >//Action Corresponding to 1/x button else if(evt.getSource()==prop) < double n1=Double.parseDouble(mainTextField.getText()); n1=1/n1; str=String.valueOf(n1); mainTextField.setText(str); >//Action Corresponding to sqrt button else if(evt.getSource()==sqrt) < double n1=Double.parseDouble(mainTextField.getText()); n1=Math.sqrt(n1); str=String.valueOf(n1); mainTextField.setText(str); >//Action Corresponding to % button else if(evt.getSource()==per) < double n1=Double.parseDouble(mainTextField.getText()); n1=(n1*num)/100; str=String.valueOf(n1); mainTextField.setText(str); >> //Add called according to previous operator void add1() < if(first==0) result=num=result+n1; String str=String.valueOf(result); mainTextField.setText(str); opt=2; if(oper2!=0) < oper1=oper2; oper2=0; >first=0; > //Sub called according to previous operator void sub() < if(first==0) result=num=result-n1; String str=String.valueOf(result); mainTextField.setText(str); opt=2; if(oper2!=0) oper1=oper2; first=0; >//Div called according to previous operator void div() < if(first==0) < if(n1==0) mainTextField.setText("Cannot divide by zero"); else result=num=result/n1; >String str=String.valueOf(result); mainTextField.setText(str); opt=2; if(oper2!=0) oper1=oper2; first=0; > //Mul called according to previous operator void mul() < if(first==0) result=num=result*n1; String str=String.valueOf(result); mainTextField.setText(str); opt=2; if(oper2!=0) oper1=oper2; first=0; >public static void main(String args[]) < Calculator obj = new Calculator(); obj.setVisible(true); >>

3.1 Output

Output of code will be like the one below.

Читайте также:  Learn about html language

Java Calculator - Calculator result

3.2 Different keys usage:

  • MC = Memory Clear sets the memory to 0
  • MR = Memory Recall uses the number in memory
  • MS = Memory Store puts the number on the display into the memory
  • M+ = Memory Add takes the number on the display, adds it to the memory, and puts the result into memory
  • mainTextField for integer calculation
  • memoryTextField for marking memory operations.

Method of calculating in calculator has been kept simple as Standard Microsoft Calculators.

Event Handling has been used where a source generates an event and a listener is notified when an event occurs say when a button is pressed using a mouse.

4. Download the Source Code

This was an example of java calculator example.

Download
You can download the full source code of this example here: Java Calculator using Swing Example

Last updated on Sept. 29, 2019

Источник

Оцените статью