-1

switch statement's default is not working as expected. when I enter other than number, control should execute default. But, it's not working as expected. And compiler throws error like Exception in thread "main" java.util.InputMismatchException. Kindly check.

import java.util.Scanner;

class Switch_Statement_2 {

    public static void main(String[] args) {
        // Add Two Entered Numbers  
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter First Number:");
        int number1 = scan.nextInt();

        System.out.println("Enter Second Number:");
        int number2 = scan.nextInt();
        

        System.out.println("Choose an Operator: + or *");
        char operator = scan.next().charAt(0);
        scan.close();

        switch(operator) {

        case '+':
            number1 += number2;      
            System.out.println("Addition of Entered Numbers is: "+number1);
            break;
            
        case '*':
            number1 *= number2;
            System.out.println("Multiplication of Entered Numbers is: "+number1);
            break;

        default:
            System.err.println("INVALID INPUT");

        }

    }

}
  • 2
    "_And compiler throws error like Exception in thread "main" java.util.InputMismatchException_" – No, that's not a compiler error; that's a run-time error. Most likely, `nextInt()` is failing because there is no next token that can be parsed into an integer. Also, you never set `operator` to anything other than `'+'`, so of course the default case will not execute. – Slaw Sep 03 '23 at 03:07
  • Thanks for reply, Marc I just added another case and asked user to input operator. But, run-time error is same. default is not working. case '*': number1 *= number2; System.out.println("Multiplication of Entered Numbers is: "+number1); break; – Murali7373 Sep 03 '23 at 03:26
  • 1
    Please update the question with new code (use "Edit"). People won't see the code you put in your comment, and formatting code in comments is impossible. – markspace Sep 03 '23 at 03:33
  • You're confusing an Exception with the `switch` keyword. The two have nothing to do with each other. If you need to catch an exception, use `try catch`. – markspace Sep 03 '23 at 03:35
  • Hi markspace, just updated the code. Please check if possible. Thank you! – Murali7373 Sep 03 '23 at 03:45

0 Answers0