I'm trying to count the total of words in a file but java is giving the total of words per line. because I'm using .hasNextLine() it doesn't calculate the total of the lines no matter how I try it.is there a way to tell java to total each line and return the value of total word of the lines
import java.io.File;//import file class
import java.io.IOException;//import file class to handle errors
import java.util.Scanner;
import java.io.FileNotFoundException;
public class readingfromafile {
public static void main(String []args) {
{
try{
File myobj = new File("C:\\Users\\cse21-037\\Documents\\assighnment java\\100 words\\brain drain.txt");
Scanner myReader = new Scanner(myobj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
int count = 1;
for (int i = 0; i < data.length() - 1; i )
{
if ((data.charAt(i) == ' ') && (data.charAt(i 1) != ' '))
{
count ;
}
}
System.out.println(count);
}
}
catch (FileNotFoundException e) {
System.out.println("error 404");
e.printStackTrace();
}
}
}
}
CodePudding user response:
Use a global variable to store totalCount of words.
public static void main(String []args) {
{
try{
File myobj = new File("C:\\Users\\cse21-037\\Documents\\assighnment java\\100 words\\brain drain.txt");
Scanner myReader = new Scanner(myobj);
int totalCount = 0;
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
int count = 1;
for (int i = 0; i < data.length() - 1; i )
{
if ((data.charAt(i) == ' ') && (data.charAt(i 1) != ' '))
{
count ;
}
}
totalCount = totalCount count;
System.out.println(count);
}
}
catch (FileNotFoundException e) {
System.out.println("error 404");
e.printStackTrace();
}
}
}
}
It should work.
CodePudding user response:
I'd do it like this:
package stackoverflow;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileWordCounter {
public static void main(final String[] args) throws IOException {
final String fileName = args != null && args.length > 0 ? args[0] : "/test/file";
final String text = Files.readString(Paths.get(fileName));
final String[] parts = text.split("\\W "); // use \\s to split whole words, use \\W to exclude non-word characters
System.out.println("Got parts:\t" parts.length);
System.out.println("Counting words...");
long counter = 0;
for (final String part : parts) {
if (part != null && part.trim().length() > 0) {
System.out.println("\t[" part "]");
counter;
}
}
System.out.println("Counted words:\t" counter);
System.out.println("All done.");
}
}