Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.55 KB | None | 0 0
  1. Scanner sc = new Scanner(System.in);
  2.  
  3. System.out.println("Please type some words, then press enter: ");
  4.  
  5. int count = 0;
  6. double sum = 0;
  7.  
  8. String input = sc.nextLine();
  9.  
  10. String[] words = input.split("\\s+"); // split by whitespace
  11.  
  12. // iterate over each word and update the stats
  13. for (String word : words) {
  14.     double wordLength = word.length();
  15.     sum += wordLength;
  16.     count++;
  17. }
  18.  
  19. // calculate the average at the end
  20. double average = 0;
  21. if (count > 0) {
  22.     average = sum / count;
  23. }
  24.  
  25. System.out.println("Average word length = " + average);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement