解析可变数量的行

时间:2013-11-04 17:27:32

标签: java parsing map

我需要解析这种输入:

  • 第一行:包含一个int值 n 1< = n< = 26 )表示下面定义的符号数
  • n 行格式如示例,括号中的值只能是 0,1,....,9 用空格分隔。第一个符号是一个字符( A,...,Z )。

每个符号(A-Z)定义一个包含相关行中所有值的集合。 { }代表一个空集。没有一个符号可以重复。

输入示例:

3
Z = { 5 6 2 }
X = { 2 5 7 }
Y = { 2 4 3 0 }

2
X = { 7 }
Y = { }

我必须存储这些集合并通过相关符号识别它们。为了实现我的目标,我使用了存储< Mapset_id>的java set_values。情侣,其中每个符号都是地图的set_id键。

HashMap<Character, List<Integer>> sets = new HashMap<Character, List<Integer>>();

这是代码的其余部分。我希望有人能给我一些建议,找到另一种方法并改善表现。

    BufferedReader r =
            new BufferedReader (new InputStreamReader(System.in));
    String line = null;

    /* Stores couple <Set_id, Set_values> */
    HashMap<Character, List<Integer>> sets = new HashMap<Character, List<Integer>>();

    /* number of sets, first line parsed */
    int n_sets = Integer.parseInt(r.readLine());

    Character set_id = null;
    Character current = null;
    List<Integer> set_values = null;

    System.out.println("DEBUG: Will perform "+n_sets+" iteration");
    while(n_sets != 0){
        set_values = new ArrayList<Integer>();
        line = r.readLine();
        set_id = new Character(line.charAt(0));

        /* Set input example : Z = { 5 6 2 } */
        for(int i=0; i<line.length(); i++){
            current = line.charAt(i);
            /* Fill values list for current set */
            if(Character.isDigit(current))
                set_values.add(Integer.parseInt(current.toString()));
        }

        /*Put current <set_id, set_values> into map */
        sets.put(set_id, set_values);
        -- n_sets;
    }

1 个答案:

答案 0 :(得分:1)

尝试使用split()来消除必须处理的空格(无论如何总是不符合你的标准)

    String[] splitLine = line.split(" ");
    for(int i=0; i<splitLine.length; i++){
                if (Character.isDigit(splitLine[i].charAt(0)))
                   set_values.add(Integer.parseInt(current.toString()));
            }
相关问题