如何在输入 int、char 和 int 时避免 java 中的 InputMismatchException

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

我是 Java 的新手,我想解决 java 中的一个简单问题。

在输入中我需要 integer a and then a character c and then another integer b 并打印输出 if the character is '+' then print a+b 等等。

输入看起来像:6+4

但是我发现这样一直报错

Exception in thread "main" java.util.InputMismatchException

我的代码:

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();
    }
}

删除双扫描仪对象并试试这个

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);
    }