2013-04-02 30 views
0

在我的程序的一部分中,我正在读取包含"ua, "的行,并将它们设置为等于我想要处理的行数。我想用数组来使这种灵活性适合我想要的许多行。使用数组允许灵活性

这是它如何与4线

,而不是有多个else if语句的作品,我想简化,这样我可以定义多个行我要处理,而不必编辑此部分

try (BufferedReader br = new BufferedReader(new FileReader(f.getAbsolutePath()))) { 

    String line1 = null, line2 = null, line3 = null, line4 = null, line = null; 
    boolean firstLineMet = false; 
    boolean secondLineMet = false; 
    boolean thirdLineMet = false; 

    while ((line = br.readLine()) != null) { 
     if (line.contains("ua, ")) { 

      if (!firstLineMet) { 
       line1 = line; 
       firstLineMet = true; 
      } else if (!secondLineMet) { 
       line2 = line; 
       secondLineMet = true; 
      } else if (!thirdLineMet) { 
       line3 = line; 
       thirdLineMet = true; 
      } else { 
       line4 = line; 
       ProcessLines(uaCount, line1, line2, line3, line4); 
       line1 = line2; 
       line2 = line3; 
       line3 = line4; 
      } 
     } 
    } 
} 
+0

您是否尝试过解决方案? –

+0

为我们说清楚。你的问题是什么? – apast

+0

而不是有多个其他if语句,我想简化这个,以便我可以定义一些我想要处理的行,而不必编辑这部分 – user2007843

回答

0

假设读取内存中的整个文件是好的,你可以使用由Files提供的方便的方法:

List<String> lines = Files.readAllLines(yourFile, charset); 
ProcessLines(uaCount, lines.get(0), lines.get(1), ...); 

或者如果y ou想要按顺序处理线路,但只能达到一定的限制:

for (int i = 0; i < limit && i < lines.length(); i++) { 
    processLine(lines.get(i)); 
} 
1

替代方案您可以采取以下措施来实现您的目标。

int counter = 0; 
int limit = 3; // set your limit 
String[] lines = new String[limit]; 
boolean[] lineMet = new boolean[limit]; 

while ((line = br.readLine()) != null) { 
    if (line.contains("ua, ")) { 
     lines[counter] = line; 
     lineMet[counter] = true; // doesn't make any sense, however 
     counter++; 
    } 
    if (counter == limit){ 
    // tweak counter otherwise previous if will replace those lines with new ones 
     counter = 0; 
     ProcessLines(uaCount, lines); // send whole array 
     lines[0] = lines[1]; // replace first line with second line 
     lines[1] = lines[2]; // replace second line with third line 
     lines[2] = lines[3]; // replace third line with fourth line 

     // ProcessLines(uaCount, lines[0], lines[1], lines[2], lines[3]); 
     // Do Something 
    } 
} 

我希望这会对你有帮助。

+0

这是我正在尝试做的。我的目标是能够改变一个变量,让我们称之为'lineNumber'这将得到我所需要的 – user2007843

+0

我认为这就是我的答案。这里我使用'limit'变量并发送整个数组,以便不必依赖于多少行。 – Smit

+0

没关系,但在处理完这些行之后,我会如何将它们设置为与下一个相等? – user2007843