我是一名Java初学者,对Java的了解非常薄弱。 对于我已经工作的代码,该代码已经计算出一个句子中的单词数,一个句子的字符总数以及每个单词的字符总数,我想添加另一个函数。
我想添加一段代码来计算单词长度的平均值,例如,如果我输入“嗨,嗨,猫狗我”,则输出为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", 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;
}
}