Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Scanner sc = new Scanner(System.in);
- System.out.println("Please type some words, then press enter: ");
- int count = 0;
- double sum = 0;
- String input = sc.nextLine();
- String[] words = input.split("\\s+"); // split by whitespace
- // iterate over each word and update the stats
- for (String word : words) {
- double wordLength = word.length();
- sum += wordLength;
- count++;
- }
- // calculate the average at the end
- double average = 0;
- if (count > 0) {
- average = sum / count;
- }
- System.out.println("Average word length = " + average);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement