import java.util.
Scanner;
public class ArithmeticOperations { public static void main(String[] args) { Scanner scanner =
new Scanner(System.in); // Create Scanner object
// Taking first number input
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
// Taking second number input
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
// Performing arithmetic operations
System.out.println("\nResults:");
System.out.println("Addition: " + (num1 + num2));
System.out.println("Subtraction: " + (num1 - num2));
System.out.println("Multiplication: " + (num1 * num2));
// Handling division by zero
if (num2 != 0) {
System.out.println("Division: " + (num1 / num2));
} else {
System.out.println("Division: Cannot divide by zero!");
}
scanner.close(); // Closing the scanner
}
}
import java.util.InputMismatchException;
// This imports the InputMismatchException class from the java.util package.
// It allows your program to use this specific exception type, which is thrown when the input
is not of the expected data type.
import java.util.Scanner;
//This imports the Scanner class, which is used to take input from the user (keyboard, file, etc.).
public class RobustCalculator {
public static void main(String[] args) {
//main method
Scanner scanner = new Scanner(System.in);
// This line is used in Java to take input from the user (keyboard).
boolean continueCalc= true;
//This line declares a boolean variable and initializes it.
while (continueCalc) {
try {
// It tries to execute the code, If an exception (error) occurs, it jumps to the catch block
System.out.print("Enter first number: ");
double num1 = Double.parseDouble(scanner.nextLine());
//Takes input from the user (as a String),Converts that input to a double value ,Stores it in a
variable named num1.
System.out.print("Enter operator (+, -, *, /): ");
String op = scanner.nextLine();
//read the operator entered till next line
System.out.print("Enter second number: ");
double num2 = Double.parseDouble(scanner.nextLine());
////Takes input from the user (as a String),Converts that input to a double value ,Stores it in a
variable named num2.
double result;
//declare type of result
switch (op) {
//select arithmetic operation
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
throw new ArithmeticException("Division by zero");
result = num1 / num2;
break;
default:
System.out.println("Invalid operator: " + op);
continue;
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
//block to handle the exception, Catch blocks prevent program crashes and deliver informative
messages to the user.
System.out.println("Error: Please enter a valid number.");
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
scanner.close();