Reputation: 21
The code needs to have a method averageLength
with the parameter String s
. The method needs to return, as a double
value, the average length of the words in s
. Assuming s
consists of only words separated by single blanks, without any leading or trailing blanks. I have a code below that finds the average length of words but it doesn't have the method averageLength
:
import java.util.Scanner;
class main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type in your sentence, then press enter: ");
String words = sc.nextLine();
int count = 0;
double sum = 0;
double average = 0;
sc = new Scanner(words);
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
if (count > 0) {
average = sum / count;
}
}
System.out.println("Average word length = " + average);
}
}
Upvotes: 0
Views: 324
Reputation:
Since Java 8 you can use DoubleStream#average
method for this purpose:
public static double averageLength(String words) {
return Arrays
// split a string into an array of
// words by spaces, returns Stream<String>
.stream(words.split(" "))
// take a word's length, returns DoubleStream
.mapToDouble(String::length)
// returns OptionalDouble
.average()
// if a value is not present, returns 0.0
.orElse(0.0D);
}
public static void main(String[] args) {
String words = "Not all questions benefit from including code " +
"but if your problem is with code you've written you " +
"should include some But don't just copy in your entire " +
"program Not only is this likely to get you in trouble " +
"if you're posting your employer's code it likely includes " +
"a lot of irrelevant details that readers will need to " +
"ignore when trying to reproduce the problem";
System.out.println(averageLength(words)); // 4.671875
}
See also: Sort semantic versions in a given array as a string
Upvotes: 0
Reputation: 1099
First, declare a method that returns a double and accepts a parameter of String
private static double returnAverageLength(String sentence){
With the help of the split()
method, we split the sentence into words
String [] words = sentence.split(" ");
With a for loop we count all characters of the sentence
for(int i=0;i<words.length;i++){
countCharacters+= words[i].length();
}
And we return the average result
return countCharacters / words.length;
Full code
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Write sentence");
String s = scanner.nextLine();
double average = returnAverageLength(s);
System.out.println("AVERAGE IS " + average);
}
private static double returnAverageLength(String sentence){
String [] words = sentence.split(" ");
double countCharacters = 0;
for(int i=0;i<words.length;i++){
countCharacters+= words[i].length();
}
return countCharacters / words.length;
}
}
OUTPUT
Write sentence
Hello From Stackoverflow
AVERAGE IS 7.33
Upvotes: 1