2012-05-12 65 views
2

我在本實驗中的任務是接受多個輸入文件,其格式與所有文件類似,只是某些文件有註釋,我想跳過註釋行。例如:Java - 掃描儀評論跳過

輸入文件:

Input file 1 

#comment: next 5 lines are are for to be placed in an array 
blah 1 
blah 2 
blah 3 
blah 4 
blah 5 

#comment: next 2 line are to be placed in a different array 
blah 1 
blah 2 

#end of input file 1 

我試圖做什麼我用了2 while循環(如果需要的話我可以張貼我的代碼)。我做了以下

while(s.hasNext()) { 
    while(!(s.nextLine().startWith("#")) { 
     //for loop used to put in array 
     array[i] = s.nextLine(); 
    } 
} 

我覺得這應該工作,但事實並非如此。我在做什麼不正確。請幫忙。先謝謝你。

回答

1

有兩個問題與您的代碼:

  1. 要調用不是在循環中一次nextLine更多。
  2. 如果沒有下一行,您的第二個while循環將失敗。

嘗試修改代碼如下:

int i = 0; 
while(s.hasNextLine()) { 
    String line = s.nextLine(); 
    if(!line.startWith("#")) { 
      array[i++] = line; 
    }  
} 
7

你失去了良好的線,應該是:

String line; 
while(!(line = s.nextLine()).startWith("#")) { 
    array[i] = line; 
} 
+0

你忘了s.hasNext() –

+0

@ThomasMueller - 我沒有,我只保留在目標代碼的本質。 – MByD

0

與您的代碼的問題是,它會讀取數組中的唯一交替行,因爲nextLine()方法會被調用兩次(一次同時測試表達式和第二次在同時身體)之前,行被讀取,而不是一次...什麼binyamin建議會爲你工作。