在我的程序的一部分中,我正在读取包含“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;
}
}
}
}
最佳答案
您可以采取以下措施来实现您的目标。
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
}
}
希望这对您有帮助。
关于java - 使用数组以实现灵活性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15771143/