我有点坚持这个问题。我试图在一个字符串中存储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);
}
答案 0 :(得分: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);
答案 1 :(得分:1)
也许这有助于你:
您必须将计算从average
移出 while循环
或者每次都会计算和打印!
我也改进了一点。 (你不需要每次都加倍)
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);
答案 2 :(得分: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。
这样,它会缩短处理周转时间。
答案 3 :(得分: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));
}
}
}
}