Create a Simple Calculator Program in Java


 

How to Create a Calculator Java Program

In this tutorial, we will learn how to create a simple calculator program in Java. This program will be able to perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

Step 1: Setting up the Project

  • Create a new Java project in your preferred IDE (Integrated Development Environment).
  • Create a new class called Calculator and make sure it has a main method.

Step 2: Designing the User Interface

  • We will use the Java Scanner class to get user input.
  • We will use System.out.println() to display the output.

Step 3: Writing the Code

Here is the code for the Calculator class:
Java
import java.util.Scanner;

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

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

        System.out.println("Enter the operator (+, -, \*, /):");
        String operator = scanner.next();

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

        double result = 0;

        switch (operator) {
            case "+":
                result = num1 + num2;
                break;
            case "-":
                result = num1 - num2;
                break;
            case "*":
                result = num1 * num2;
                break;
            case "/":
                if (num2 != 0) {
                    result = num1 / num2;
                } else {
                    System.out.println("Error: Division by zero is not allowed.");
                    return;
                }
                break;
            default:
                System.out.println("Error: Invalid operator.");
                return;
        }

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

Step 4: Running the Program

  • Compile and run the program.
  • Enter two numbers and an operator when prompted.
  • The program will display the result of the operation.

Conclusion

In this tutorial, we learned how to create a simple calculator program in Java. We used the Scanner class to get user input and a switch statement to perform different operations based on the user's input. You can extend this program to include more features such as handling multiple operators and decimal numbers.
I hope this helps! Let me know if you have any questions.

Post a Comment

Hello Guys I hope You Are Well If You Need Any Help so Please Send Comment then We Solve these Problems

Previous Post Next Post