Calculator Program In Java

Calculator Program In Java | Code, Scientific Calculator Program, AWT

Calculator Program In Java: Java is a high-level, object-oriented programming language that was first released in 1995. It is a popular choice for building complex and robust software applications, ranging from web and mobile applications to enterprise systems.

One of the main advantages of Java is its platform independence, which means that programs written in Java can be run on any system that has the Java Virtual Machine (JVM) installed, without needing to recompile the code for each platform. This makes Java highly portable and reduces the amount of time and effort required to maintain and update applications.

Java Program

In addition to its portability, Java also offers a range of features that make it a powerful programming language for a wide range of applications. These features include built-in support for multi-threading, automatic memory management, and a large standard library of reusable code.

Java is widely used in industries such as finance, healthcare, and technology, and it is a highly sought-after skill for developers. As businesses continue to rely more heavily on technology, the demand for skilled Java developers is only expected to grow, making it a valuable skill for future career opportunities.

How to make a calculator in Java with GUI?

To make a calculator in Java with a GUI, you can use the Swing library. Swing provides a variety of components that you can use to create a user interface, such as buttons, text fields, and labels.

To create a calculator with a GUI, you will need to:

  1. Create a new Java class and extend the JFrame class.
  2. Add the Swing library to your project.
  3. Create a JPanel to hold the calculator’s components.
  4. Add buttons for the calculator’s operations and numbers.
  5. Add text fields for the user to enter the numbers and to display the results.
  6. Add labels to describe the text fields and to display the operation that the user has selected.
  7. Write code to handle the events that occur when the user interacts with the calculator.

Calculator Program In Java

This program prompts the user to enter two numbers and an operator (+, -, *, /). It then performs the corresponding operation and displays the result.

The program first creates a Scanner object to read input from the user. It then prompts the user to enter the two numbers and the operator and stores them in variables num1, num2, and, respectively.

Next, the program uses an ifelse statement to determine which arithmetic operation to perform based on the operator entered. If the operator is not one of the valid options, the program displays an error message and exits.

Finally, the program displays the result of the calculation using System.out.println(). The + operator is used to concatenate strings and variables to form the output string.

import java.util.Scanner;

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

    Scanner input = new Scanner(System.in);

    System.out.print("Enter the first number: ");
    double num1 = input.nextDouble();

    System.out.print("Enter the second number: ");
    double num2 = input.nextDouble();

    System.out.print("Enter an operator (+, -, *, /): ");
    char operator = input.next().charAt(0);

    double result;

    if (operator == '+') {
      result = num1 + num2;
    } else if (operator == '-') {
      result = num1 - num2;
    } else if (operator == '*') {
      result = num1 * num2;
    } else if (operator == '/') {
      result = num1 / num2;
    } else {
      System.out.println("Invalid operator entered.");
      return;
    }

    System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
  }
}

Calculator Program in Java Applet

Creating a calculator using Java Applet involves graphical user interface (GUI) components. Below is a basic example of a calculator implemented as a Java Applet. Note that Java Applets are now considered somewhat outdated due to security concerns, and Java itself is being phased out in modern web development.

import java.applet.Applet;
import java.awt.Button;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CalculatorApplet extends Applet implements ActionListener {
private String buffer;
private String operator;
private double result;

public void init() {
setLayout(new GridLayout(4, 5));

buffer = “”;
operator = “”;
result = 0.0;

addButton(“7”);
addButton(“8”);
addButton(“9”);
addButton(“/”);
addButton(“C”);

addButton(“4”);
addButton(“5”);
addButton(“6”);
addButton(“*”);
addButton(“sqrt”);

addButton(“1”);
addButton(“2”);
addButton(“3”);
addButton(“-“);
addButton(“1/x”);

addButton(“0”);
addButton(“.”);
addButton(“=”);
addButton(“+”);
}

private void addButton(String label) {
Button button = new Button(label);
button.addActionListener(this);
add(button);
}

public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();

if (action.matches(“[0-9]|\\.”)) {
buffer += action;
} else if (action.matches(“[+\\-*/]”)) {
operator = action;
result = Double.parseDouble(buffer);
buffer = “”;
} else if (action.equals(“=”)) {
double secondOperand = Double.parseDouble(buffer);

switch (operator) {
case “+”:
result += secondOperand;
break;
case “-“:
result -= secondOperand;
break;
case “*”:
result *= secondOperand;
break;
case “/”:
if (secondOperand != 0) {
result /= secondOperand;
} else {
buffer = “Error”;
}
break;
}

buffer = Double.toString(result);
operator = “”;
} else if (action.equals(“C”)) {
buffer = “”;
operator = “”;
result = 0.0;
} else if (action.equals(“sqrt”)) {
if (!buffer.isEmpty()) {
double operand = Double.parseDouble(buffer);
if (operand >= 0) {
buffer = Double.toString(Math.sqrt(operand));
} else {
buffer = “Error”;
}
}
} else if (action.equals(“1/x”)) {
if (!buffer.isEmpty()) {
double operand = Double.parseDouble(buffer);
if (operand != 0) {
buffer = Double.toString(1 / operand);
} else {
buffer = “Error”;
}
}
}

repaint();
}

public void paint() {
showStatus(buffer);
}
}

Scientific calculator program in Java

A scientific calculator program in Java is a program that performs advanced mathematical functions beyond basic arithmetic operations. These functions include trigonometry, logarithms, exponents, and more.

Here is an example code for a basic scientific calculator program in Java:

import java.util.Scanner;

public class ScientificCalculator {

   public static void main(String[] args) {

      Scanner input = new Scanner(System.in);

      System.out.print("Enter a number: ");
      double num1 = input.nextDouble();

      System.out.print("Enter an operator (+, -, *, /, sin, cos, tan, log): ");
      String operator = input.next();

      double result = 0.0;

      if (operator.equals("+")) {
         System.out.print("Enter another number: ");
         double num2 = input.nextDouble();
         result = num1 + num2;
      }
      else if (operator.equals("-")) {
         System.out.print("Enter another number: ");
         double num2 = input.nextDouble();
         result = num1 - num2;
      }
      else if (operator.equals("*")) {
         System.out.print("Enter another number: ");
         double num2 = input.nextDouble();
         result = num1 * num2;
      }
      else if (operator.equals("/")) {
         System.out.print("Enter another number: ");
         double num2 = input.nextDouble();
         result = num1 / num2;
      }
      else if (operator.equals("sin")) {
         result = Math.sin(num1);
      }
      else if (operator.equals("cos")) {
         result = Math.cos(num1);
      }
      else if (operator.equals("tan")) {
         result = Math.tan(num1);
      }
      else if (operator.equals("log")) {
         result = Math.log(num1);
      }
      else {
         System.out.println("Invalid operator entered.");
         return;
      }

      System.out.println("Result: " + result);
   }
}

This program takes input from the user for a number and an operator (+, -, *, /, sin, cos, tan, log) and performs the corresponding mathematical operation using if-else statements. The Math class in Java is used to perform trigonometric and logarithmic functions. The program then outputs the result of the calculation.

Calculator program in Java using String

A calculator program in Java using Strings can be created to take user input as strings and perform mathematical operations on them. Here’s an example code:

import java.util.Scanner;

public class StringCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        String num1 = scanner.nextLine();
        System.out.print("Enter the second number: ");
        String num2 = scanner.nextLine();
        System.out.print("Enter the operator (+, -, *, /): ");
        String operator = scanner.nextLine();

        double result = 0;

        switch (operator) {
            case "+":
                result = Double.parseDouble(num1) + Double.parseDouble(num2);
                break;
            case "-":
                result = Double.parseDouble(num1) - Double.parseDouble(num2);
                break;
            case "*":
                result = Double.parseDouble(num1) * Double.parseDouble(num2);
                break;
            case "/":
                result = Double.parseDouble(num1) / Double.parseDouble(num2);
                break;
            default:
                System.out.println("Invalid operator!");
                break;
        }

        System.out.println("Result: " + result);
    }
}

In this code, the program takes input from the user as strings for the first number, second number, and operator. The input is then converted to double using the Double.parseDouble() method and mathematical operations are performed on them using a switch case statement. The result is then printed to the console using System.out.println().

Calculator program in Java using switch case

A calculator program in Java using switch case is a program that allows the user to perform basic mathematical operations such as addition, subtraction, multiplication, and division. The program uses the switch case statement to determine which operation the user wants to perform based on their input.

Here is an example code for a calculator program in Java using switch case:

import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter first number: ");
        double num1 = input.nextDouble();
        
        System.out.println("Enter second number: ");
        double num2 = input.nextDouble();
        
        System.out.println("Choose an operation (+, -, *, /): ");
        char operator = input.next().charAt(0);
        
        double result;
        
        switch(operator) {
            case '+':
                result = num1 + num2;
                System.out.println(num1 + " + " + num2 + " = " + result);
                break;
            case '-':
                result = num1 - num2;
                System.out.println(num1 + " - " + num2 + " = " + result);
                break;
            case '*':
                result = num1 * num2;
                System.out.println(num1 + " * " + num2 + " = " + result);
                break;
            case '/':
                result = num1 / num2;
                System.out.println(num1 + " / " + num2 + " = " + result);
                break;
            default:
                System.out.println("Invalid operator entered.");
                break;
        }
        
        input.close();
    }

}

In this program, the user is prompted to enter two numbers and select an operation to perform using the switch case statement. The program then calculates the result and displays it to the user.

Simple calculator program in Java using AWT

A simple calculator program in Java using AWT (Abstract Window Toolkit) is a graphical user interface (GUI) based calculator that uses AWT components to display the calculator and accept user input. The program takes input from the user through the GUI and performs basic arithmetic operations like addition, subtraction, multiplication, and division.

The AWT package in Java provides several classes for creating and handling GUI components, such as buttons, labels, and text fields. The ActionListener interface is also used to handle the button events.

Here’s an example code for a simple calculator program in Java using AWT:

import java.awt.*;
import java.awt.event.*;

public class SimpleCalculator extends Frame implements ActionListener {
    TextField tf;
    Button b1, b2, b3, b4;

    SimpleCalculator() {
        tf = new TextField();
        tf.setBounds(30, 50, 200, 30);
        add(tf);

        b1 = new Button("+");
        b1.setBounds(30, 100, 50, 50);

        b2 = new Button("-");
        b2.setBounds(90, 100, 50, 50);

        b3 = new Button("*");
        b3.setBounds(150, 100, 50, 50);

        b4 = new Button("/");
        b4.setBounds(210, 100, 50, 50);

        add(b1);
        add(b2);
        add(b3);
        add(b4);

        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);

        setSize(300, 200);
        setLayout(null);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String s = e.getActionCommand();
        if (s.equals("+")) {
            tf.setText("+");
        } else if (s.equals("-")) {
            tf.setText("-");
        } else if (s.equals("*")) {
            tf.setText("*");
        } else if (s.equals("/")) {
            tf.setText("/");
        }
    }

    public static void main(String[] args) {
        new SimpleCalculator();
    }
}

In this code, we create a TextField to display the result, and four Buttons for addition, subtraction, multiplication, and division. We add ActionListener to each button to perform the corresponding operation. When a button is clicked, the actionPerformed() method is called and the corresponding operator is displayed in the text field.

Calculator program in Java using if else

The calculator program in Java using if else statement allows users to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. The program prompts the user to input two numbers and an operator of their choice. It then performs the operation based on the operator input using if else statements and displays the result.

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number: ");
        double num1 = scanner.nextDouble();

        System.out.print("Enter second number: ");
        double num2 = scanner.nextDouble();

        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = scanner.next().charAt(0);

        double result;

        if (operator == '+') {
            result = num1 + num2;
        } else if (operator == '-') {
            result = num1 - num2;
        } else if (operator == '*') {
            result = num1 * num2;
        } else if (operator == '/') {
            result = num1 / num2;
        } else {
            System.out.println("Invalid operator!");
            return;
        }

        System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
    }
}

This program uses if else statements to check which operator the user has inputted and performs the corresponding operation. If an invalid operator is entered, it displays an error message. The program then prints the result of the operation.

Calculator program in Java using for loop

A calculator program in Java using for loop is a program that performs basic mathematical operations using a for loop. In this program, the user is asked to enter two numbers and the operation they want to perform, which is then carried out using a for loop.

Here is an example of a Calculator program in Java using for loop:

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter second number: ");
        int num2 = scanner.nextInt();

        System.out.print("Enter operation (+, -, *, /): ");
        char operator = scanner.next().charAt(0);

        int result = 0;

        for (int i = 0; i < 1; i++) {
            if (operator == '+') {
                result = num1 + num2;
            } else if (operator == '-') {
                result = num1 - num2;
            } else if (operator == '*') {
                result = num1 * num2;
            } else if (operator == '/') {
                result = num1 / num2;
            } else {
                System.out.println("Invalid operator!");
            }
        }

        System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
    }
}

 

In this program, we first import the java.util.Scanner package to accept user input. Then, we prompt the user to enter the two numbers and the operation they want to perform using the Scanner.nextInt() and Scanner.next().charAt(0) methods respectively.

We then initialize the result variable to 0 and perform the desired operation using an if-else statement within a for loop. If the operator is not valid, an error message is displayed.

Finally, we print out the result of the operation using System.out.println().

Calculator program in Java using Swing

A calculator program in Java using Swing is a graphical user interface (GUI) application that allows users to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. The program is built using the Swing library, which provides a set of components for creating a modern and customizable user interface. The user inputs the numbers and operators through buttons displayed on the calculator interface, and the result is displayed in a text field. Here is a sample code for a basic calculator program in Java using Swing:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener {
    JTextField display;
    JButton btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnAdd, btnSub, btnMul, btnDiv, btnEqual, btnClear;

    public Calculator() {
        setTitle("Calculator");
        setSize(200, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        display = new JTextField(16);
        display.setEditable(false);
        add(display, BorderLayout.NORTH);

        JPanel panel = new JPanel(new GridLayout(4, 4));
        btn1 = new JButton("1");
        btn1.addActionListener(this);
        panel.add(btn1);
        //Add more buttons to the panel...

        add(panel, BorderLayout.CENTER);

        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String input = e.getActionCommand();
        //Perform the operation based on the input...
    }

    public static void main(String[] args) {
        Calculator calculator = new Calculator();
    }
}

Calculator Program in Java Using Class and Objects

In this program, we have a Calculator class that contains methods to perform basic mathematical operations. The CalculatorProgram class creates an instance of the Calculator class and interacts with the user to input numbers and select an operation. Based on the user’s choice, the corresponding method from the Calculator class is called to perform the calculation, and the result is displayed.

import java.util.Scanner;

class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}

public int subtract(int num1, int num2) {
return num1 – num2;
}

public int multiply(int num1, int num2) {
return num1 * num2;
}

public int divide(int num1, int num2) {
return num1 / num2;
}
}

public class CalculatorProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator calculator = new Calculator();

System.out.print(“Enter the first number: “);
int num1 = scanner.nextInt();

System.out.print(“Enter the second number: “);
int num2 = scanner.nextInt();

System.out.println(“\nSelect an operation:”);
System.out.println(“1. Addition”);
System.out.println(“2. Subtraction”);
System.out.println(“3. Multiplication”);
System.out.println(“4. Division”);

System.out.print(“Enter your choice (1-4): “);
int choice = scanner.nextInt();

switch (choice) {
case 1:
int sum = calculator.add(num1, num2);
System.out.println(“Result: ” + sum);
break;
case 2:
int difference = calculator.subtract(num1, num2);
System.out.println(“Result: ” + difference);
break;
case 3:
int product = calculator.multiply(num1, num2);
System.out.println(“Result: ” + product);
break;
case 4:
int quotient = calculator.divide(num1, num2);
System.out.println(“Result: ” + quotient);
break;
default:
System.out.println(“Invalid choice!”);
}

scanner.close();
}
}

Calculator program in Java using Scanner class

A calculator program in Java using the Scanner class allows the user to enter input values directly into the program from the console. This program uses a while loop to continuously prompt the user for input until they choose to exit the program. The Scanner class is used to read user input values as Strings and then convert them to their corresponding numeric data types using the parse method. The program then performs the desired calculation based on the user input and displays the result.

Here’s an example code for a basic calculator program using the Scanner class:

import java.util.Scanner;

public class Calculator {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      double num1, num2, result;
      char operator;
      
      while (true) {
         System.out.print("Enter operator (+, -, *, /) or 'q' to quit: ");
         operator = input.next().charAt(0);
         
         if (operator == 'q') {
            break;
         }
         
         System.out.print("Enter first number: ");
         num1 = input.nextDouble();
         
         System.out.print("Enter second number: ");
         num2 = input.nextDouble();
         
         switch(operator) {
            case '+':
               result = num1 + num2;
               break;
            case '-':
               result = num1 - num2;
               break;
            case '*':
               result = num1 * num2;
               break;
            case '/':
               result = num1 / num2;
               break;
            default:
               System.out.println("Invalid operator!");
               continue;
         }
         
         System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
      }
      
      input.close();
   }
}

Note: All the above-mentioned dates are tentative, So kindly visit the official website for all the information. If you find any inaccuracies or improper content on the website, please e-mail help[@]universityadmission2023[dot]inThere is no guarantee that the information on this website is accurate. It is provided solely for informational purposes.

Leave a Reply

Your email address will not be published. Required fields are marked *