2017-05-17 29 views
1

我想從文件中讀取一組數字,然後在第一行之間的隔離線(這讓我們知道需要多少行要工作,在這種情況下,5)和第七行(請注意,這僅僅是一個例子,行的範圍會有所變化),以便我可以填充格式爲(0 1 98,0 2 5, ...,4 3 15)。現在我的代碼設法得到(0 1 98,0 2 5,0 3 16,0 4 16)添加到列表中,但其餘的都沒有。我不確定我做錯了什麼。任何幫助將非常感激。外環不工作(JAVA)

例輸入:

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

它可能工作,但節點沒有你認爲它的價值。要麼調試,要麼添加一些打印語句來檢查變量的值 – Stultuske

+0

相信我,我已經試圖調試一個小時了,並且沒有找到任何修復程序。節點也絕對是正確的價值。 –

+0

你能讀取並打印所有行嗎? – Marged

回答

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; 
     } 
    } 
+0

太感謝你了,這解決了我的問題。已經連續近18個小時都不敢相信我忽視了這一點。再次感謝。 –