Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
.... And I don't see where I made mistake
This is what I have done:

Java
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);
Posted
Updated 23-Feb-12 15:49pm
v4

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
 
Share this answer
 
v2
Comments
Manfred Rudolf Bihy 23-Feb-12 20:55pm    
I see you answered before me! Correct as ever ;)
5!
Sergey Alexandrovich Kryukov 23-Feb-12 21:05pm    
Before you? Only because it's short. Thank you, Manfred.
--SA
Alexander Alekseyevich Fedoseev 23-Feb-12 21:48pm    
Thank you a lot!
Sergey Alexandrovich Kryukov 23-Feb-12 21:58pm    
You are welcome.
Good luck,
--SA
Monjurul Habib 26-Feb-12 6:12am    
5!
Just a little change:
Java
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);


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
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-Feb-12 20:53pm    
Yes, of course. A 5.
--SA
Manfred Rudolf Bihy 23-Feb-12 20:53pm    
Thanks!
Alexander Alekseyevich Fedoseev 23-Feb-12 21:47pm    
Thank you a lot!
Monjurul Habib 26-Feb-12 6:12am    
5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900