有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何计算文本文件的行数

import java.io.*;
import java.util.*;

public class Practices {

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

这是我的文本文件:

生存还是毁灭这是
这个问题
现在呢
就这样吧

Scanner input =new Scanner(new File("C:/Users/Charlie/workspace/Summerexercises/src/hamlet.txt"));
            int countwords=0;
            int countlines=0;
            int countchar=0;

            while(input.hasNext())
            {
                String word = input.next();
                countwords++;
            }
            System.out.println("total words= "+ countwords);

这是while循环,它计算行数,但不能正常工作

while(input.hasNextLine())
                {
                    String lines= input.nextLine();
                    countlines++;
                }
                System.out.println("total lines= "+ countlines);




                input.close();
              }
    }

共 (4) 个答案

  1. # 1 楼答案

    **此循环将计算行数**

    int count = 0;
    while (scanner.hasNextLine()) {
        count++;
        scanner.nextLine();
    }
    
  2. # 3 楼答案

    在第一个循环中,您消耗了所有扫描仪内容,而第二个循环从未执行过。这样做:

    Scanner input =new Scanner(new File("C:/Users/Charlie/workspace/Summerexercises/src/hamlet.txt"));
    int countwords=0;
    int countlines=0;
    int countchar=0;
    while(input.hasNext())
    {
        String word = input.next();
        countwords++;
    }
    System.out.println("total words= "+ countwords);
    input.close();
    input =new Scanner(new File("C:/Users/Charlie/workspace/Summerexercises/src/hamlet.txt"));
    while(input.hasNextLine())
    {
        String lines= input.nextLine();
        countlines++;
    }
    System.out.println("total lines= "+ countlines);
    input.close();
    
  3. # 4 楼答案

    你必须重新从文件的开头开始。当第一个循环结束时,您将指向EOF,因此第二个循环中不计算任何行。尝试注释第一个循环并运行此程序