ArrayList的ArrayList的ArrayList错误检索

时间:2012-07-23 08:09:55

标签: java arraylist

我正在创建一个ArrayList的Arraylist的ArrayList,并按照下面的方式填充它。它正确填充它。我通过调试和println计算出来了。但是当我尝试检索那些整数时,它无法正常工作,并向我显示我为ArrayList变量的所有值读取的文件中的最后一个整数。

下面是我填充的代码,它运行良好。

    Scanner sc = new Scanner(new File("e1.txt"));
    Scanner lineSc;
    String lineStr;


    String lineRegEx = "(\\d+),(\\d+)";
    Pattern linePattern = Pattern.compile(lineRegEx);
    Matcher matcher;

    Integer vertex = 0, edge = 0, length = 0;
    String strE, strL ;
    ArrayList<Integer> tmpLE = new ArrayList<Integer>() ;
    ArrayList<ArrayList<Integer>> singleV = new ArrayList<ArrayList<Integer>>() ;

    sc.useDelimiter("\\n");


    int i = 0, j = 0;
    while (sc.hasNextLine()) {
        lineStr = sc.nextLine();
        lineSc = new Scanner(lineStr);

        lineSc.nextInt(); 

        matcher = linePattern.matcher(lineStr);

        while (matcher.find()) {
                strE = matcher.group(1);
                edge = Integer.parseInt(strE);
                tmpLE.add(EI, edge);
                strL = matcher.group(2);
                length = Integer.parseInt(strL);
                tmpLE.add(LI, length);

                singleV.add(j ,tmpLE);
                graph.add(i, singleV);
                //System.out.println (graph.get(i).get(j).get(0));
                //System.out.println (graph.get(i).get(j).get(1));
                ++j;
        }
        j = 0;
        ++i;
        lineSc.close();
    }
    sc.close();

}

以下是我用于检索但不能正常运行的代码

    for (int i = 0; i < N; ++i) {
        Integer minLen = graph.get(i).get(0).get(LI);
        System.out.println (minLen);
        Integer choosenEdge = 0;
        for (int j = 0; j < graph.get(i).size(); ++j) {
            ArrayList<Integer> tmpArr = graph.get(i).get(j);
            System.out.print(tmpArr.get(LI) + "  " + minLen); //Wrong Output
            if (minLen > tmpArr.get(LI))
            {
                minLen = tmpArr.get(LI);
                choosenEdge = graph.get(i).get(j).get(EI);
                System.out.println (choosenEdge); // Wrong Output
            }

        }

    }

1 个答案:

答案 0 :(得分:1)

您需要为每个ArrayList<Integer>循环创建matcher.find()

 tmpLE = new ArrayList<Integer>() ;
 strE = matcher.group(1);
 edge = Integer.parseInt(strE);
 tmpLE.add(EI, edge);
 strL = matcher.group(2);
 length = Integer.parseInt(strL);
 tmpLE.add(LI, length);

 singleV.add(j ,tmpLE);
 graph.add(i, singleV);