In: Computer Science
In Java, Using ArrayList and HashSet data structures, as well as
their methods, obtain following from some input text file:
Total number of characters used,without counting spaces and
punctuation, total number of words used; Number of words, counting
each word only once; Total number of punctuation characters;Number
of words that are of size six or more;Number of words that are used
only once
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author paramesh
*/
public class CountWords {
public static int totalChars(ArrayList<String> words){
int totalChars = 0;
for(int i=0;i<words.size();i++){
totalChars = totalChars +words.get(i).length();
}
return totalChars;
}
public static int totalCountWithoutSpaces(ArrayList<String>
words){
return words.size();
}
public static int totalWords(ArrayList<String> words){
int totalWords = 0;
ArrayList<String> alreadyVisited = new
ArrayList<String>();
//counting starts from here
for(int i=0;i<words.size();i++){
boolean visited = false;
for(int j=0;j<alreadyVisited.size();j++){
if(words.get(i).equals(alreadyVisited.get(j))){
visited = true;
}
}
if(!visited){
totalWords++;
alreadyVisited.add(words.get(i));
}
}
return totalWords;
}
public static void main(String args[]) {
System.out.println("Oppgave A");
ArrayList<String> words = new
ArrayList<String>();
try {
File fr = new File("Alice.txt");
Scanner sc = new Scanner(fr);
while (sc.hasNext()) {
String line = sc.nextLine();
String[] space = line.split(" ");
for(int i=0;i<space.length;i++){
words.add(space[i]);
}
}
} catch (Exception e) {
System.out.println("File not found");
}
//calling methods
System.out.println("Total words: "+totalWords(words));
}
}