打印出文件包含的行数

时间:2014-02-05 16:30:39

标签: java

当我输入有效的.txt文件时,我的代码什么都不做。我想打印文件包含的行数。谁能告诉我为什么现在什么也没发生?

public class Task3
{
    public static void main(String[] args) throws FileNotFoundException
    {
        // instance variables
        int characterCount = 0;
        int wordCount = 0;
        int lineCount = 0;
        // create a Scanner object to read in file name from console input
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter the file name: ");
        String filename = in.next();
        File inputFile = new File(filename);


        // create a Scanner object to read the actual text file
        Scanner inFile = new Scanner(inputFile);

        int lines = 0;

        while (inFile.hasNextLine())
        { // enter while loop if there is a complete line available
        in.nextLine();
            lines++;
            // increase line counter variable
            }
          System.out.println(lines); 

4 个答案:

答案 0 :(得分:1)

您不是从文件中读取行,而是从标准输入中读取它们。

答案 1 :(得分:1)

在这个循环中:

    while (inFile.hasNextLine())
    { // enter while loop if there is a complete line available
        in.nextLine();
        lines++;
        // increase line counter variable
    }

您正在使用System.in的扫描仪,而不是您为该文件创建的扫描仪。因此,对nextLine的调用将等待您的输入,而不是转到文件中的下一行。这就是为什么似乎没有发生任何事情。

in.nextLine替换为inFile.nextLine,它将有效。

答案 2 :(得分:0)

变化:

in.nextLine();

要:

inFile.nextLine();

答案 3 :(得分:0)

添加System.out.println(inputFile.exists())以查看您没有创建新文件。

相关问题