2012-05-12 64 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建议会为你工作。