Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.ArrayList;
  3. import java.io.FileNotFoundException;
  4. import java.io.*;
  5. /**
  6. * Chris Pfeiffer, APCS P. 7
  7. * Ch14 Quiz
  8. */
  9. public class Wordcount
  10. {
  11. public static void main() throws IOException
  12. {
  13. File file = null;
  14. Scanner in = null;
  15. String line = null, word1, word2;
  16. int wordLen = 0, lenLine = 0, totalLen = 0, counter = 0, avg = 0, index = 0;
  17.  
  18. try
  19. {
  20. file = new File("source.txt");
  21. in = new Scanner(file);
  22. }
  23. catch(FileNotFoundException ex)
  24. {
  25. System.out.println("CANNOT OPEN FILE");
  26. System.exit(1);
  27. }
  28.  
  29. int len1 = 0, len2 = 0;
  30. while(in.hasNext())
  31. {
  32. line = in.next();
  33. lenLine = line.length();
  34.  
  35. counter++;
  36.  
  37.  
  38. for(int i = 0; i < lenLine; i++)
  39. {
  40. if(!Character.isLetterOrDigit(line.charAt(i)))
  41. {
  42. word1 = line.substring(0, i);
  43. word2 = line.substring(i + 1, lenLine);
  44. len1 = word1.length();
  45. len2 = word2.length();
  46. counter++;
  47. }
  48. }
  49.  
  50. if(len1 != 0 || len2 != 0)
  51. {
  52. totalLen += len1;
  53. totalLen += len2;
  54. }
  55. else
  56. totalLen +=lenLine;
  57.  
  58. }
  59.  
  60. avg = (int) totalLen/counter;
  61.  
  62. System.out.println("Number of words: " + counter + " Average length: " + avg);
  63.  
  64. in.close();
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement