Java Programming help?
I am having trouble getting my code to work.correctly. here is the problem: You are to write a program that reads data from a file, calculates statistics on that data, and then outputs the statistics to either another file or to the screen, depending on what the user wants.
I can not get my program to get the the numbers from the file and pass to the different methods. Please help.
here is my code
import java.util.*;
import java.io.*;
public class statisticsTest {
public static void main(String[] args)
throws FileNotFoundException {
double [] array;
double median;
double max;
double min;
double mean;
double mode;
double sd;
int line;
int count = 0;
Scanner console = new Scanner(System.in);
System.out.print("File name: ");
String name = console.nextLine();
Scanner input = new Scanner(new File(name));
int arraysize=input.nextInt();
array = new double [arraysize];
while(count < arraysize){
count++;
}
System.out.println("There are " + count + " numbers in your input file.");
max=max(array);
System.out.println("Max: "+ max);
min=min(array);
System.out.println("Min: "+ min);
mean=mean(array);
System.out.println("Mean: "+ mean);
median=median(array);
System.out.println("Median: "+ median);
System.out.println("Mode: ");
System.out.println("Standard Deviation: " + sd( array ) );
}
public static double median(double[] array){
int size = array.length;
double temp;
for (int i=0; i<size; i++){
for (int j=0; j<size-i-1; j++){
if(array[j]>array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1]=temp;
}
}
}
double med;
if ((size % 2) == 0){
med = (array[size / 2] + array[size / 2 - 1]) / 2.000;
} else {
med = array[size / 2];
}
return med;
}
public static double max(double[] array){
double max = array[0];
for (int j = 1; j < array.length; j++){
if (array[j] > max) {
max = array[j];
}
}
return max;
}
public static double min(double[] array){
double min = array[0];
for (int j = 1; j < array.length; j++){
if (array[j] < min){
min = array[j];
}
}
return min;
}
public static double mean(double[] array){
double mean = 0;
for (int i=0; i<array.length; i++){
mean = mean + array[i];
}
return mean / array.length;
}
public static double sd ( double[] array ){
double mean = 0;
double n = array.length;
if ( n < 2 ){
return Double.NaN;
}
for ( int i=0; i<n; i++ ){
mean += array[i];
}
mean /= n;
double sum = 0;
for ( int i=0; i<n; i++ ){
final double v = array[i] - mean;
sum += v * v;
}
return Math.sqrt( sum / ( n - 1 ) );
}
public static int mode(int [] array) {
int[] tally = new int[array.length];
for(int i = 0; i < tally.length; i++) {
tally[i] = 0;
}
for(int i = 0; i < array.length; i++) {
int value = array[i];
tally[value]++;
}
int maxIndex = 0;
for(int i = 1; i < tally.length; i++) {
if(tally[i] > tally[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
}