这个线程解决了! [英] This thread is solved!

查看:63
本文介绍了这个线程解决了!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

....而且我看不到我在哪里犯了错误
这是我所做的:

.... And I don''t see where I made mistake
This is what I have done:

int count = 0;
int sum = 0;
int average = 0;
File file = new File("dvorak.txt");
Scanner inputFile = new Scanner(file);




if (!file.exists())
{
    System.out.println("No file");
    System.exit(0);
}
while(inputFile.hasNext())
{
    String text = inputFile.nextLine();
    int length = text.length();
    sum = sum + length;
    average = sum / length;



}
System.out.println(average);

推荐答案

请从循环中删除average的计算并正确计算平均值.在循环中,收集行数(您根本不用计算),并在循环完成后,将sum除以行数(而不是length,即长度)来计算平均值当前行的行,不应在循环外部声明.

—SA
Please remove calculation of average out of the loop and calculate the average correctly. In the loop, collect number of lines (you don''t count them at all) and after the loop is done, calculate average by dividing sum by number of lines (and not by length, which is the the length of a current line and should not be declared outside of the loop).

—SA


只需一点改动:
Just a little change:
int count = 0;
int average = 0;
File file = new File("dvorak.txt");
Scanner inputFile = new Scanner(file);


if (!file.exists())
{
    System.out.println("No file");
    System.exit(0);
}
int totalLength = 0;
int lineCount = 0;
while(inputFile.hasNext())
{
    String text = inputFile.nextLine();
    lineCount += 1;
    totalLength += text.length();
}
average = totalLength / lineCount;
System.out.println(average);



这应该够了吧.您计算文件中所有行的长度,然后除以收集的行数.

问候,

曼弗雷德(Manfred)



That should do the trick. You count all the line lengths in the file and then divide by the number of lines collected.

Regards,

Manfred


这篇关于这个线程解决了!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆