Answer to Question #287845 in Java | JSP | JSF for Mengal

Question #287845

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.

1
Expert's answer
2022-01-16T04:16:35-0500
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");
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog