more accurate average of array data

• 10-28-2012, 10:41 PM
jwl
more accurate average of array data
I can calculate the average somewhat but not as close as I would like. I'm working with the average method.

Code:

```package test; import java.io.File; import java.io.IOException; import java.util.Scanner; public class Test {   private Scanner read;   private int numData;   int[] data;         // Open File   private void openFile() {       try {           read = new Scanner(new File("File.txt")); // reading integers from a file       }       catch (IOException e) {           System.out.println("Could not open file input");       }   }     //Close File   private void closeFile() {       read.close();   }     //Read File and Store it in an array of size numData   private int[] readInputFile() {       openFile();       numData = read.nextInt(); // Creating size of array from file       read.nextLine();       data = new int[numData]; //Storing integers in an array         for (int i = 0; i < numData; i++) {             data[i] = read.nextInt();             //System.out.printf("%s\n", data[i] + " array item: " +  i); //testing         }       closeFile();       return data;   }     private void average() {       data = readInputFile(); //array created from file       int num = 0;       for (int i = 0; i < (data.length - 1); i++) { //data.length - 1 because the first number in file           num = num + data[i];                        //crates the size of the array (I think that is correct)       }       System.out.println("Average: " + num/(data.length - 2));   }       private void test() {       average();   }       public static void main(String[] args) {         new Test();     }         public Test() {         test();   } }```
when I calculate the average on a calculater I get 119.1666............7. The program displays the int value of 120 which doesn't seem right. Do I need to do some sort of conversions or something?
• 10-28-2012, 10:52 PM
.paul.
Re: more accurate average of array data
the int datatype is integer which are whole numbers
try using float datatype instead...
• 10-28-2012, 11:14 PM
jwl
Re: more accurate average of array data
Ok, This is better

Code:

```private void average() {       data = readInputFile(); //array created from file       double num = 0;       for (int i = 0; i < (data.length); i++) {           num = num + data[i];       }       System.out.println("Average: " + num/(data.length - 1)); //data.length - 1 because the first number in file crates the size of the array   }```
float was better but double matches the value of the calculator.