Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.ArrayList;
- import java.io.FileNotFoundException;
- import java.io.*;
- /**
- * Chris Pfeiffer, APCS P. 7
- * Ch14 Quiz
- */
- public class Wordcount
- {
- public static void main() throws IOException
- {
- File file = null;
- Scanner in = null;
- String line = null, word1, word2;
- int wordLen = 0, lenLine = 0, totalLen = 0, counter = 0, avg = 0, index = 0;
- try
- {
- file = new File("source.txt");
- in = new Scanner(file);
- }
- catch(FileNotFoundException ex)
- {
- System.out.println("CANNOT OPEN FILE");
- System.exit(1);
- }
- int len1 = 0, len2 = 0;
- while(in.hasNext())
- {
- line = in.next();
- lenLine = line.length();
- counter++;
- for(int i = 0; i < lenLine; i++)
- {
- if(!Character.isLetterOrDigit(line.charAt(i)))
- {
- word1 = line.substring(0, i);
- word2 = line.substring(i + 1, lenLine);
- len1 = word1.length();
- len2 = word2.length();
- counter++;
- }
- }
- if(len1 != 0 || len2 != 0)
- {
- totalLen += len1;
- totalLen += len2;
- }
- else
- totalLen +=lenLine;
- }
- avg = (int) totalLen/counter;
- System.out.println("Number of words: " + counter + " Average length: " + avg);
- in.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement