In this guide, we will develop a simple calculator program in Java that can perform basic arithmetic operations like addition, subtraction, multiplication, and division. The program will take input from the user, process the input, and display the result of the operation.
The task is to create a calculator that can handle the following operations:
The program should prompt the user to input two numbers and an operator, then perform the corresponding operation and display the result.
import java.util.Scanner; /** * Simple Calculator Program in Java * Author: https://www.javaguides.net/ */ public class SimpleCalculator < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); // Prompt the user for input 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; // Perform the operation 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."); return; >break; default: System.out.println("Invalid operator! Please use +, -, *, or /."); return; > // Display the result System.out.println("The result is: " + result); > >
Enter first number: 5 Enter second number: 3 Enter an operator (+, -, *, /): + The result is: 8.0
Enter first number: 10 Enter second number: 2 Enter an operator (+, -, *, /): / The result is: 5.0
Enter first number: 7 Enter second number: 3 Enter an operator (+, -, *, /): * The result is: 21.0
Enter first number: 10 Enter second number: 0 Enter an operator (+, -, *, /): / Error! Division by zero.
This simple calculator program demonstrates how to take user input in Java and perform basic arithmetic operations. By using a switch statement, the program can handle different operators and provide the corresponding result. This program is a good starting point for beginners to learn about user input, control flow, and basic arithmetic in Java.