在Java中正确使用Scanner.hasNextLine?

在Java中正确使用Scanner.hasNextLine?,java,Java,我目前正在为我的班级做一个项目,在这个项目中,我必须对文本文件中的数字数组进行排序。我创建了一个读卡器来查看.txt文件中有多少个值,以便定义数组大小,但是我的while()语句在使用.hasNextLine时似乎被破坏了,进入了一个永无止境的循环。这是我的密码: File unsorted = new File("unsorted.txt"); int j = 0;//Counter for the amount of slots in the array Syst

我目前正在为我的班级做一个项目,在这个项目中,我必须对文本文件中的数字数组进行排序。我创建了一个读卡器来查看.txt文件中有多少个值,以便定义数组大小,但是我的while()语句在使用.hasNextLine时似乎被破坏了,进入了一个永无止境的循环。这是我的密码:

    File unsorted = new File("unsorted.txt");

    int j = 0;//Counter for the amount of slots in the array

    System.out.println("Executing file reading...");

    try
    {

        Scanner input = new Scanner(unsorted);

        while(input.hasNextLine()){

            j++;//Scanner to count the length of the array

            System.out.println(j);

        }

        input.close();

        System.out.println("The file has " + j + " lines.");

    }
    catch (IOException ex){

        System.out.printf("ERROR: Could not read file 'unsorted.txt'", ex);

    }

    System.out.println("File read.");

try{}之后的打印行永远不会打印,相反,当我在while()循环中有J print时,它会一直打印下去。目前,该文件中有7个值,都是数字。

当您调用时,
hasNextLine()
方法的值只会更改--只有机会更改。
nextLine()。只要检查它是否有更多的线。所以它一直说“是”,因为它仍然在第一行。谢谢你。。。我现在觉得自己相当愚蠢……可能是重复的