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);
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With