javainputmismatchexception

How to avoid InputMismatchException in java while taking input in int,char and int


I am new to Java and I want to solve a simple problem in java.

In input I need to take an integer a and then a character c and then another integer b And print the output if the character is '+' then print a+b And so on like this.

The input looks like : 6+4

But I find an error continuously like this

Exception in thread "main" java.util.InputMismatchException

My Code:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Scanner sc1 = new Scanner(System.in);
    
    try {
        int a, b, ans = 0;
        char c;
        
        a = sc.nextInt();
        c = sc1.next().charAt(0);
        b = sc.nextInt();

        if (c=='+') {
            ans = a + b;
        } else if (c=='-') {
            ans = a - b;
        } else if (c=='*') {
            ans = a * b;
        } else if (c=='/') {
            ans = a / b;
        }

        System.out.println(ans);
    } finally {
        sc.close();
        sc1.close();
    }
}

Solution

  • remove the double scanner object and try this

    Scanner sc = new Scanner(System.in);
    
        int a, b, ans = 0;
        String c;
        String input = sc.nextLine();
        Pattern pattern = Pattern.compile("([0-9]+)([+*/-])([0-9]+)");
        Matcher matcher = pattern.matcher(input);
        if (!matcher.find()) {
            System.out.println("Invalid command");
        } else {
            a = Integer.valueOf(matcher.group(1));
            c = matcher.group(2);
            b = Integer.valueOf(matcher.group(3));
    
            if (c.equals("+")) {
                ans = a + b;
            } else if (c.equals( "-")) {
                ans = a - b;
            } else if (c.equals( "*")) {
                ans = a * b;
            } else if (c.equals("/")) {
                ans = a / b;
            }
    
            System.out.println(ans);
        }