将输入拆分为整数

时间:2015-05-04 10:24:57

标签: java

我正在尝试拆分通过扫描仪获得的输入并将方括号内的整数拆分并将它们全部放入单独的树集中,并根据行中的运算符执行操作。我在尝试解析输入并将其添加到不同的树集中时遇到问题,即使将其转换为整数,我仍然会获得InputMismatchException。想知道我哪里出错了。

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int times = in.nextInt();
        //iterate through number of times
        for (int i = 0; i < times; i++) {
            int num = in.nextInt();
            System.out.println(num)
        }
    }
}

我接受的输入是

6
[1,2,3] + [1,4,5]
[5,4,7,11] - [5,7]
[1,2,3] * [1,4,5]
[5,17,51,2,51] + [1,3,12,5,44,66,82]
[7,13,23,11,10] - [11,13,14,7,8,9,10]
[7,13,23,11,10] * [11,13,14,7,8,9,10]

Where my question is from

1 个答案:

答案 0 :(得分:0)

nextInt无法正确解析[],+等字符(如果它与+ 4之类的数字分开}而不是+4,它只代表4)。

这就是为什么当您尝试使用[1,2,3] + [3,4]来解析nextInt之类的字符串时,由于InputMismatchException,您将获得[

解析文件的最简单方法之一可能是

int times = in.nextInt();
in.nextLine();//nextInt will not consume line separator, we need to do it explicitly
for (int i = 0; i < times; i++) {
    String line = in.nextLine();
    parse(line);
}

其中parse方法可以来自

private static final Pattern p = Pattern
        .compile("\\[(?<set1>\\d+(?:,\\d+)*)\\]"    // match first [1,2,3] and place it in group named set1
                + "\\s(?<operator>[-+*])\\s"        // match operator, one of - + or *
                + "\\[(?<set2>\\d+(?:,\\d+)*)\\]"); // match second [2,3,4] and place in group named set2

private static void parse(String text) {
    Matcher m = p.matcher(text);
    if (m.matches()) {

        String[] set1 = m.group("set1").split(",");
        String[] set2 = m.group("set2").split(",");
        String operator = m.group("operator");

        if (operator.equals("+")){
            //handle sum of sets
        } 
        //handle rest of operators
        else if (operator.equals("-")){
            //...
        }
        //...

    } else {
        System.out.println("wrong text format:");
        System.out.println(text);
    }
}