Java programming help?
There are several things I can not get my code to do. First I need it to read an external file which contains numbers and put it into an array. Next I need it to count how many numbers are in the file. Next, I cant get my main method to call the mode. I'm sure there may be other mistakes in my code, so any help will be greatly appreciated.
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;
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];
System.out.println("There are " + arraysize + " 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 = array[0];
for (int i=0; i<array.length; i++){
mean = mean + array[i];
}
return mean / array.length - 1;
}
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;
}
}