I'm currently working on an assignment for my intro programming class and I need to be able to assign the contents of a file to variable. The file contains a text paragraph. I need to be able to eventually count all characters and words in the text file.
What I have so far:
import java.io.*;
import java.util.Scanner;
public class CountWords {
public static void main(String[] args) throws IOException {
File inFile = new File("CountWordsTestFile.txt");
Scanner input = new Scanner(inFile);
String text = input.nextLine();
int words = 0, cha = text.length(), character = 0;
System.out.println(text);
System.out.println("The file contains");
System.out.println(words + " words");
System.out.println((cha + 1) + " characters");
input.close();
}
}
Here is simplified version of Java program to count characters and words in a file. I assume here that the file is a text file and words in the file are separated by one or more spaces only, not by any delimiter.
Hope it fits your requirement.
Edit : Simple Code as your request