2015-05-09 97 views
0

我必須通讀一個文件,取出行並將它們添加到自定義服務類,然後將該服務類添加到timeTable中。然而返回的timeTable是空的。空集返回時沒有錯誤

  • 假設文件的格式是正確的

這是文件:

3 
v1 
1 v2 v3 
2 v4 
3 

v2 
1 
2 v1 v4 
3 

代碼:

while ((line = buffReader.readLine()) != null) { 

    if (firstLine){ 
     //Set session 
     numberOfSessions = Integer.parseInt(line.trim()); 
     firstLine = false; 

    } else if (line.trim().isEmpty()) { 
     correctSession = 0;  
    } else if(correctSession < numberOfSessions + 1) { 
     //Split the current line 
     String[] splitLine = line.split(" "); 

     //Check if it is the "Name" line 
     if (correctSession == 0) { 
      sourceName = line.trim(); 
      //Increase correct session 
      correctSession++; 
     } else { 
      //Add it to timetable as a service 
      for (int i = 1;i < lineSplit.size();i++) { 
       //Venue(String) 
       Venue source = new Venue(sourceName); 
       Venue destination = new Venue(splitLine[i]); 

       //Service(venue, venue, int) 
       Service service = new Service(source,destination,Integer.parseInt(splitLine[0])); 

       timeTable.addService(service); /* This does not seem to be working*/ 
      } 
      //Increase correct session 
      correctSession++; 
     } 
    }   
} 
//Close the reader 
buffReader.close(); 

結果:

Actual: [] 
Expected: [Departs v1 after session 1 for v3, Departs v1 after session 2 for v4, Departs v1 after session 1 for v2, Departs v2 after session 2 for v4, Departs v2 after session 2 for v1] 

回答

0

除非我遺漏了一些東西,否則你似乎在迭代錯誤的東西(你的變量名稱非常相似)。但對此,

for (int i = 1;i < lineSplit.size();i++) { 

應該是(因爲數組在0開始)像

for (int i = 0;i < splitLine.length;i++) { 

或者,使用The For-Each Loop

for (String destinationName : splitLine) { 
    //Venue(String) 
    Venue source = new Venue(sourceName); 
    // Venue destination = new Venue(splitLine[i]); 
    Venue destination = new Venue(destinationName); 
+0

的原因,我用我= 1,因爲我不要讀第一個元素,因爲這是一個數字,我只想要名稱v1或v2。 –

相關問題