外循环不起作用(java)

时间:2017-05-17 16:40:55

标签: java list file loops nested

我正在尝试从文件中读取一组数字然后隔离第一行之间的行(这让我们知道需要处理多少行,在本例中为5)和第七行(请注意,这只是一个示例,行的范围可能会发生变化),以便我可以填充格式为(0 1 98,0 2 5,...,4 3 15)的列表。现在我的代码设法将(0 1 98,0 2 5,0 3 16,0 4 16)添加到列表中但不添加其余部分。我不确定我做错了什么。任何帮助将非常感激。

示例输入:

5
0 1 98 2 5 3 16 4 16
1 0 13 2 47 3 3 4 40
2 0 71 1 51 3 43 4 30
3 0 20 1 94 4 46
4 0 1 1 10 2 28 3 15
2
2 3
2
0 1

public static void t() {
    List<String> L = new ArrayList();
    try {
        BufferedReader f = new BufferedReader(new FileReader("graph.txt"));
        String s = f.readLine();
        int nodes = Integer.parseInt(s);

        int c = -1;
        int c1 = 2;
        int c2 = 3;

        for (int i = 0; i < nodes; i++) {
            s = f.readLine();
            String z [] = s.split(" ");
            String start = z[0];

            for (int j = 0; j < z.length; j++) {
                int t = c+c1;
                int t2 = c+c2;

                if (t >= z.length) {
                    break;
                }
                String des = z[t];

                if (t2 >= z.length+1) {
                    break;
                }
                String weight = z[t2];

                L.add(start + " " + des + " " + weight);

                c1+=2;
                c2+=2;
            }
        }

        for (int i = 0; i < L.size(); i++) {
            System.out.println(L.get(i));
        }           
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

1 个答案:

答案 0 :(得分:1)

您只需要在外部循环中重置C个变量。

    for (int i = 0; i < nodes; i++) {
        s = f.readLine();
        String z [] = s.split(" ");
        String start = z[0];

        // Declare the variables here, otherwise code is the same
        int c = -1;
        int c1 = 2;
        int c2 = 3;

        for (int j = 0; j < z.length; j++) {
            int t = c+c1;
            int t2 = c+c2;

            if (t >= z.length) {
                break;
            }
            String des = z[t];

            if (t2 >= z.length+1) {
                break;
            }
            String weight = z[t2];

            L.add(start + " " + des + " " + weight);

            c1+=2;
            c2+=2;
        }
    }