Java 仅使用给定的导入,无法从文件中获取每一行的长度

Java 仅使用给定的导入,无法从文件中获取每一行的长度,java,Java,该程序读取名为“Readme.txt”的文件,显示每一行的行号,然后在读取所有行后显示平均行长 我这里的问题是我 线程“main”java.util.NoSuchElementException中的异常:未找到任何行 注意:我只想在代码中使用导入,其他什么都不用 我尝试使用sc.nextLine().length()来确定每行的长度,但是,我遇到了错误消息 这是我的密码: import java.io.File; import java.io.IOException; import java.u

该程序读取名为“Readme.txt”的文件,显示每一行的行号,然后在读取所有行后显示平均行长

我这里的问题是我 线程“main”java.util.NoSuchElementException中的异常:未找到任何行

注意:我只想在代码中使用导入,其他什么都不用

我尝试使用sc.nextLine().length()来确定每行的长度,但是,我遇到了错误消息

这是我的密码:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class LineReader {

public static void main(String[] args) throws IOException {

    Scanner sc = new Scanner(new File("Readme.txt"));
    int count = 0;
    double total = 0;
    while (sc.hasNextLine()) {
        count++;
        total += sc.nextLine().length();
        System.out.println(count + " " + sc.nextLine());


    }

    double avg = total / count;
    System.out.println("The average line length is " + avg );

}


每次调用
Scanner.nextLine()
都会占用一行。当前在循环中调用它两次。将引用保存在本地。例如

while (sc.hasNextLine()) {
    String line = sc.nextLine();
    count++;
    total += line.length();
    System.out.println(count + " " + line);
}
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    count++;
    total += line.length();
    System.out.println(count + " " + line);
}