Расчет средней длины слова

Я новичок в 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;
    }

}

person Mat    schedule 04.08.2014    source источник
comment
Для чего все эти скобки, это так сбивает с толку. У вас нет сигнатуры метода для вашего метода усреднения   -  person u3l    schedule 04.08.2014
comment
Знаете что помогает? Код с правильным отступом и форматированием с последовательным размещением скобок. Ваш код не работает, потому что они не закрывают правильные блоки операторов. Это становится очевидным после того, как я переформатировал ваш код в IntelliJ IDEA (я просто добавил его и нажал на переформатирование, поэтому, если ваш код был здесь полным, то это должна быть его точная копия).   -  person EpicPandaForce    schedule 04.08.2014
comment
Я действительно извиняюсь за запутанные скобки, я продолжал добавлять их, чтобы избавиться от ошибок, предлагающих мне их добавить. Спасибо Zhuinden за то, что потратили время на форматирование моего кода, и спасибо, Доверие, я просто потратил некоторое время на попытку добавить подходящую сигнатуру метода!   -  person Mat    schedule 04.08.2014
comment
@Mat, к счастью, переформатирование не заняло много времени, потому что форматирование IntelliJ IDEA действительно умное, если вы правильно его настроите. Я использую следующую настройку: stackoverflow.com/questions/24649971/   -  person EpicPandaForce    schedule 04.08.2014


Ответы (3)


Используйте метод разделения. Вот пример:

//returns the average word length of input string s
//the method is of double type since it will likely not return an integer
double avgWordLength(String s){

   String delims=",;. ";//this contains all the characters that will be used to split the string (notice there is a blank space)

   //now we split the string into several substrings called "tokens"
   String[] tokens = s.split(delims);

   int total=0;//stores the total number of characters in words;

   for(int i=0; i<tokens.length(); i++){

      total += tokens[i].length(); //adds the length of the word to the total

   }

   double avg = total/tokens.length();

   return avg;

}

И вот оно.

person VACN    schedule 04.08.2014

вы можете попробовать вот так

String input = "hello Alpha this is bravo";
        String[] strArray = input.split(" ");
        float totalChars = 0;
        for(String s : strArray){
            totalChars += s.length();
        }
        float words = strArray.length;
        float averageWordLength = (float)(totalChars/words);
        System.out.println(averageWordLength);
person amit bhardwaj    schedule 04.08.2014

Вам просто нужно вызвать что-то вроде:

public static double getAverageCharLength(String str) {
    String words[] = str.split(" ");
    int numWords = words.length;
    int totalCharacters = 0;
    for(int i = 0; i < numWords; i++)
         totalCharacters = totalCharacters + words[i].length();

    return totalCharacters/numWords;
}

Я не могу сказать вам, где вы ошибаетесь, потому что я не могу понять беспорядок, который представляет собой ваш код. Но это логика, которой вы должны следовать.

Примечание. Средняя длина слова вычисляется неправильно, если ваши слова содержат специальные символы, такие как апострофы. Я не уверен, нужно ли вам следить за этим в вашем случае, но если вы это сделаете, изучите регулярные выражения, чтобы указать, какие символы игнорировать, и используйте методы String, такие как contains().

Также обратите внимание, что у вас нет сигнатур методов для следующих двух методов, которые вы пытаетесь определить:

{
    //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();
}

Возможно, попробуйте просмотреть синтаксис Java в документации оракула, если вы не знаете, как правильно писать эти методы.

person u3l    schedule 04.08.2014