当前位置: 动力学知识库 > 问答 > 编程问答 >

java - My program compiles, but it gives me a 0.0 average when there is no 0 in source file

问题描述:

I am working on an assignment, my program is supposed to read grades from a file and output an average. My code compiles, but the output is always 0.0.

Code is as follows:

import java.util.Scanner;

import java.io.File;

import java.io.FileReader;

import java.io.FileNotFoundException;

public class testScores

{

public static void main ( String [] args )

{

int i;

int c;

double [] testScores = new double[7];

i=0;

try

{

Scanner scan = new Scanner( new File ( "testScores.txt") );

while( scan.hasNext() )

{

String temp = scan.nextLine();

testScores[i] = Double.parseDouble(temp);

i++;

}

scan.close();

}

catch ( FileNotFoundException fnfe )

{

System.out.println("Unable to find the testScores.txt file. Program terminating.");

}

catch (Exception e)

{

e.printStackTrace();

}

double avgStart = 0;

double avgFinal;

int gradeCount = 1;

while ( i < testScores.length)

{

avgStart += testScores[i];

i++;

}

avgFinal = avgStart / i;

System.out.println("The final average of all of the test scores in the file testScores.txt are " + avgFinal + ".");

}

}

Please give any insight into it. I'am not sure how the code gets to zero.

网友答案:

If you divide by an integer then your result will be an integer

With integer division

1.0 / 2 == 0

so change

avgFinal = avgStart / i;

to

avgFinal = avgStart / (double) i;
网友答案:

Your i value is already equal to lenght of array. So its not going in while loop.

 int j = 0;
int gradeCount = 1;    
  while ( j < testScores.length)
     {
    avgStart =   avgStart += testScores[i];
       j++;
     }  

avgFinal = avgStart / i;

System.out.println("The final average of all of the test scores in the file testScores.txt are " + avgFinal + ".");

  }
网友答案:

Can you please explain exactly what the program is supposed to do. I am pretty sure you want to reset i to 0 (i = 0) before the last while.

网友答案:

First of all - the program is not very well written. It is all static, doesn't follow the java object oriented programming paradigm. I guess it is OK for a students program though.

First check if the file is properly read. If you are reading line by line you should use while( scan.hasNextLine() )

The way you have written it testScores is always 7 items. If the file is longer you will get ArrayIndexOutOfBoundsException, if there are less you will get incorrect average because it will fill the array with 0. You can check the java collections for example ArrayList.

And now the actual problem that causes your program to return 0:

You use the i variable in the first cycle for scanning. Its value is increased when you use it in the second cycle. You can use another variable or set the value of i to 0 before the second while and it will work.

分享给朋友:
您可能感兴趣的文章:
随机阅读: