Я новичок в java с очень слабым пониманием java. К моему уже работающему коду, который уже вычисляет количество слов в предложении, общее количество символов предложения и общее количество символов для каждого слова, я хотел бы добавить еще одну функцию.
Я хотел бы добавить фрагмент кода, который вычисляет среднее значение длины слова, например, если я наберу "привет, привет, кошечка, собака i", результат будет 2,4. (Поскольку общее количество символов в этом предложении равно 12, деленное на количество слов (5 слов) дает среднее значение 2,4).
Ниже приведен фрагмент кода, над которым я работаю, и это то, что я создал на основе многих руководств, но все они учат средним числам, а не длинам слов. Я думаю, что мой код должен сначала подсчитать сумму символов для каждого слова (word.length), а затем разделить ее на сумму слов (sentence.length). Но, похоже, это не работает. Не могли бы вы помочь мне исправить этот фрагмент кода?
{
//prints out average word length
int length = wordcount / word.length ;
sum = sum + word.length / sentence length; //this counts the sum of characters of words and divides them by the number of words to calculate the average
System.out.println("The average word length is " + sum);} //outputs the sum calculated above
{
Ниже приведен мой полный код, который поможет вам лучше понять, что я имею в виду. Спасибо тебе за помощь!
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in); //This adds a scaner/text window to the program.
while(true)
{ // have created infinite loop.
System.out.print("Enter your text or enter 'quit' to finish the program: ");
String sentence = in.nextLine();
if(sentence.equals("quit"))
{ // if enterd value is 'quit' than it comes out of loop
break;
}
else
{ //else if 'quit' wasn't typed it, the program displays whats underneath.
System.out.println("You have entered: "
+ sentence); // to print what the user has entered in the text window/scanner.
System.out.println("The total number of characters is " + sentence.length()
+ "."); // to print the total number of characters
System.out.println("This piece of text has " + countWords(sentence)
+ " words."); //this method counts the number of words in the entered sentence.
String[] words =
sentence.split(" "); // to get the individual words, splits them when the free space (" ") is found.
int maxWordLength = 0;
int wordLength = 0;
for(int i = 0; i < words.length; i++)
{
wordLength = words[i].length();
if(wordLength > maxWordLength)
{ //This piece of code is an array which counts the number of words with the same number of characters.
maxWordLength = wordLength;
}
}
int[] intArray = new int[maxWordLength + 1];
for(int i = 0; i < words.length; i++)
{
intArray[words[i].length()]++;
}
for(int i = 1; i < intArray.length; i++)
{
System.out.printf("There are " + "%d word(s) of length %d<\n>", intArray[i], i);
}
System.out.println("The numbers of characters for each word:"); //word.length method counts the number of characters for each word.
for(int i = 0; i < words.length; i++)
{
System.out.println(words[i] + " = " + words[i].length() + " characters");
}
}
}
}
{
//prints out average word length
int length = wordcount / world.length;
sum = sum + word.length / sentence
length; //this counts the sum of characters of words and divides them by the number of words to calculate the average
System.out.println("The average word length is " + sum);
} //outputs the sum calculated above
{
in.close();
}
private static int countWords(String str)
{ //this piece of code splits the words when the space (" ") is found and prints out the length of words.
String words[] = str.split(" ");
int count = words.length;
return count;
}
}