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);
}
}