Practical3 Prakash
Practical3 Prakash
Our goal is to develop a Java program that takes an arithmetic operator as a string and performs the corresponding
operation on two numbers provided by the user. The program will be user-friendly, allowing them to input the operator and
numbers and display the result of the operation.
Program :
import java.util.Scanner;
double result = 0;
boolean isValidOperator = true;
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 {
isValidOperator = false;
System.out.println("Error: Cannot divide by zero.");
}
break;
default:
isValidOperator = false;
System.out.println("Error: Invalid operator. Please use
one of the following: +, -, *, /");
}
if (isValidOperator) {
System.out.println("Result: " + result);
}
scanner.close();
}
}
Output :