计算特定行中的字符数

时间:2014-06-09 11:41:43

标签: java count

我正在读取文件并检查行数,字符数和最长行,我想知道文件第二行中的字符数。我该怎么办?

    Scanner input = new Scanner(new FileReader("C:/.../mrr569.fasta"));
    int lines = 0;
    int characters = 0;
    int maxCharacters = 0;
    String longestLine = "";

    while (input.hasNextLine()) {
        String line = input.nextLine();
        lines++;
        characters += line.length();

        if (maxCharacters < line.length()) {
            maxCharacters = line.length();
            longestLine = line;
        }

    }
    System.out.println(lines);
    System.out.println(characters);
    System.out.println(longestLine);

2 个答案:

答案 0 :(得分:0)

您需要跟踪您所在的线路。因此,创建一个变量lineNo

int lineNo=1;

您还需要在第二行存储字符数:

int charsInSecondLine=0;

并在while循环结束时递增此变量:

lineNo++;

然后在while循环中(在增量之前)添加一个if语句,检查它是否是第二行

if(lineNo==2){
    charsInSecondLine=line.length();
}

所以代码变成:

Scanner input = new Scanner(new FileReader("C:/.../mrr569.fasta"));
int lines = 0;
int characters = 0;
int maxCharacters = 0;
int lineNo = 1;
int charsInSecondLine = 0;
String longestLine = "";

while (input.hasNextLine()) {
    String line = input.nextLine();
    lines++;
    characters += line.length();

    if (maxCharacters < line.length()) {
        maxCharacters = line.length();
        longestLine = line;
    }

    if(lineNo==2){
        charsInSecondLine=line.length();
    }
    lineNo++;
}
System.out.println(lines);
System.out.println(characters);
System.out.println(longestLine);
System.out.println(charsInSecondLine);

答案 1 :(得分:-1)

在循环中添加一些条件。例如

if(line.startsWith(">")) {
   continue;
}

或添加行计数器并根据您的条件。