计算平均字长

问题描述 投票:0回答:3

我是一个初学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;
    }

}
java average mean
3个回答
0
投票

你可以尝试这样的

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

0
投票

您只需要调用是这样的:

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

我真的不能告诉你,你要去哪里错了,因为我无法理解的混乱那是你的代码。但是,这是你应该遵循的逻辑。

注意:这将不能正确计算的平均字长,如果你的字包含特殊字符,如单引号。我不知道,如果你需要看出来的,在你的情况,但如果这样做,看看正则表达式来指定要忽略哪些字符,并使用Stringcontains()方法。

另外请注意,您有以下两种方法你想没有定义方法签名:

{
    //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语法在Oracle文档如果你是如何去正确地写这些方法不能确定。


0
投票

使用split方法。下面是一个例子:

//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;

}

有你有它。

© www.soinside.com 2019 - 2024. All rights reserved.