Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of lines, words, and characters in a text file

Tags:

java

file

input

I am trying to take input from a user, and print the amount of lines, words, and characters in a text file. However, only the amount of words is correct, it always prints 0 for the lines and characters.

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

public class TextFileInfoPrinter
{  
    public static void main(String[]args) throws FileNotFoundException        
    { 
            Scanner console = new Scanner(System.in);           

            System.out.println("File to be read: ");
            String inputFile = console.next();

            File file = new File(inputFile);
            Scanner in = new Scanner(file);

            int words = 0;
            int lines = 0;
            int chars = 0;

            while(in.hasNext())
            {
                in.next();
                words++;
            }

            while(in.hasNextLine())
            {
                in.nextLine();
                lines++;
            }

            while(in.hasNextByte())
            {
                in.nextByte();
                chars++;
            }

            System.out.println("Number of lines: " + lines);
            System.out.println("Number of words: " + words);
            System.out.println("Number of characters: " + chars);
    }
}
like image 280
user2138453 Avatar asked Dec 26 '22 08:12

user2138453


1 Answers

try

    int words = 0;
    int lines = 0;
    int chars = 0;
    while(in.hasNextLine())  {
        lines++;
        String line = in.nextLine();
        chars += line.length();
        words += new StringTokenizer(line, " ,").countTokens();
    }
like image 150
Evgeniy Dorofeev Avatar answered Dec 29 '22 10:12

Evgeniy Dorofeev