1

我有点卡在这个问题上。我试图在一个字符串中存储 1 个或多个单词,找到所有单词组合的长度,然后将其除以单词数以找到平均值。我需要在 while 循环中执行此操作(这是作业的目标)

当我输入“Hello my name is”时,它返回的长度为

Result:  
5  
2  
4  
2  

但我想要的是添加这些结果,然后将其除以单词的数量

5+2+4+2 = 13  
13/4 = 3.25

这是我到目前为止所拥有的:

Scanner in = new Scanner(System.in);

int counter = 0;
double sum = 0;

while (in.hasNext()) {
    String word = in.next();
    double totalchar = word.length();
    sum = totalchar + sum;
    counter++;


    double average = 0;
    if (counter > 0) {
        average = sum / counter;

    }
    System.out.println(average);
}
4

4 回答 4

1

只需将average计算和打印移出while循环:

while (in.hasNext()) {
    String word = in.next();
    if (word.equals("exit")) {
        break;
    }
    double totalchar = word.length();
    sum = totalchar + sum;
    counter++;
}
double average = 0;
if (counter > 0) {
    average = sum / counter;
}
System.out.println(average);
于 2013-03-22T06:12:48.137 回答
1

也许这对您有帮助:您必须从while 循环之外
移动计算, 否则每次都会计算和打印! average

我也改进了一点。(你不需要每次都加倍)

Scanner scanner = new Scanner(System.in);

int sum = 0;
int counter = 0;

while (in.hasNext())
{
    sum += in.next().length();
    counter++;
}

double average = 0.0;
if (counter > 0)
    average = sum / counter;

System.out.println(average);
于 2013-03-22T06:18:47.377 回答
1

请参阅下面的增强版本:

    int counter = 0;
    int sum = 0; // not yet needed to be of type double
    String word = null;

    while (in.hasNext()) {
        word = in.next();
        sum += word.length();
        counter++;
    }

    double average = 0;
    if (counter > 0) {
        average = sum / counter;
    }
    System.out.println(average);

当它们将在循环中重新分配时,请在外部声明变量。

将您的计数器检查放在循环内是不好的,因为您将一遍又一遍地创建平均值以及检查计数器是否为 0。
这样,它会减慢您的处理周转时间。

于 2013-03-22T06:21:22.003 回答
1

以下示例使用 BufferedReader:

import java.util.*;
import java.io.*;
class WordAmount {
public static void main(String... args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";

while((line=br.readLine())!=null) {
   if(line.length() > 0) {
   String[] words = line.split(" ");
   int totalWords = words.length;
   int totalChars = 0;
   System.out.println("Number of words: "+totalWords);
   for(int i=0;i<words.length;i++) {
      System.out.println("Length 0f "+words[i]+" : "+words[i].length());
      totalChars += words[i].length();
   }
   System.out.println("Average count :"+ ((double)totalChars/totalWords));
  }
}
}
}
于 2013-03-22T06:37:16.350 回答