Thread: more accurate average of array data

1. Member Join Date
Jul 2012
Posts
93
Rep Power
0 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.

Java Code:
package test;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Test {
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 File and Store it in an array of size numData
private int[] readInputFile() {
openFile();
numData = read.nextInt(); // Creating size of array from file
data = new int[numData]; //Storing integers in an array
for (int i = 0; i < numData; i++) {
//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?  Reply With Quote

2. Member Join Date
Jun 2012
Posts
73
Blog Entries
1
Rep Power
0 Re: more accurate average of array data

the int datatype is integer which are whole numbers
try using float datatype instead...  Reply With Quote

3. Member Join Date
Jul 2012
Posts
93
Rep Power
0 Re: more accurate average of array data

Ok, This is better

Java 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.  Reply With Quote Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•