If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here's a simple calculator program in Java that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division:
javaCopy code
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Calculator!");
System.out.println("Available Operations: ");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.print("Enter the operation number (1/2/3/4): ");
int choice = scanner.nextInt();
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
double result = 0;
switch (choice) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero is not allowed.");
return;
}
break;
default:
System.out.println("Invalid choice. Please select a valid operation.");
return;
}
System.out.println("Result: " + result);
scanner.close();
}
}
Example usage:
yamlCopy code
Welcome to the Calculator!
Available Operations:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter the operation number (1/2/3/4): 3
Enter the first number: 12.5
Enter the second number: 3
Result: 37.5
In this program, we use a switch
statement to handle different arithmetic operations based on the user's choice. The program prompts the user to select an operation (1 for addition, 2 for subtraction, 3 for multiplication, 4 for division), and then takes two input numbers. Depending on the chosen operation, it performs the corresponding calculation and prints the result. The program also includes error handling to prevent division by zero.
Feel free to extend and customize this calculator program to include more functionality or additional operations if needed.
Comments: 0