Advertisement
advictoriam

Untitled

Jan 11th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.69 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. /**
  4.    Determines the average number of characters for words in a string.  
  5.    Input: a string of one or more lines containing words
  6.    Output: the average number of characters per word in the string
  7.       to two decimal places
  8. */
  9. public class WordAvg
  10. {
  11.    public static void main(String[] args)
  12.    {
  13.       Scanner in = new Scanner(System.in);
  14.      
  15.       int numOfWords = 0;
  16.       int avgLength = 0;
  17.      
  18.       while (in.hasNext())
  19.       {
  20.          String word = in.next();
  21.  
  22.          avgLength += word.length();
  23.          numOfWords++;
  24.       }
  25.  
  26.       // more work here
  27.       System.out.printf("%.2f\n", (float)avgLength / (float)numOfWords);
  28.    }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement