java - 使用数组以实现灵活性

标签 java arrays bufferedreader

在我的程序的一部分中,我正在读取包含“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/

相关文章:

java - 设置要使用 BufferedReader 读取的文件的相对路径

java - Hibernate JPA 和 Spring javax.persistence.TransactionRequiredException : no transaction is in progress (2)

java - 无效不调用 onDraw()

java - 在 Java 中使用 FileReader 和 BufferedReader 正确读取文件

java - 如何跳过 csv 文件中的一些空行并继续读取有数据的行?

php - 如何将值数组从 android 发送到 php

java - 如何将 Openllet OWL2 推理器(或任何其他)与 Jena TDB 一起使用?

java - Docx4j 用 XML 中的图片替换文本

c 内联汇编字符数组转短

java - 数组中的元素