Write a program to implement the calculator’s basic functionality with an exception handler that deals with non-numeric operands; then write another program without using an exception handler to achieve the same objective. Your program should display a message that informs the user of the wrong operand type before exiting.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
System.out.println("Operand:");
int a = in.nextInt();
System.out.println("Operator(+ - / *):");
String operator = in.next();
System.out.println("Operand:");
int b = in.nextInt();
switch (operator) {
case "+":
System.out.println(a + b);
break;
case "-":
System.out.println(a - b);
break;
case "*":
System.out.println(a * b);
break;
case "/":
System.out.println(a / b);
break;
default:
System.out.println("Invalid operator");
}
} catch (Exception e) {
System.out.println("Invalid operand");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Operand:");
int a = in.nextInt();
System.out.println("Operator(+ - / *):");
String operator = in.next();
System.out.println("Operand:");
int b = in.nextInt();
switch (operator) {
case "+":
System.out.println(a + b);
break;
case "-":
System.out.println(a - b);
break;
case "*":
System.out.println(a * b);
break;
case "/":
System.out.println(a / b);
break;
default:
System.out.println("Invalid operator");
}
}
}
Comments
Leave a comment