Friday, 6 September 2013

Program reads in the contents of a file into an array, and display both the console and write to a file

Program reads in the contents of a file into an array, and display both
the console and write to a file

I am writing a program that prompts the user for a file name. I have to
assume that the file contains an integer representing the number of n data
values, followed by a series of n floating numbers(which was given to me
in a file called RandomFloats), each written on a separate line. This
program should read in the contents of the RandomFloats file into an
array, and then both display in the console and write to a file the
following data: the number of floating point numbers in the array, the
lowest and highest number in the array, the total and the average. Here is
my code so far(I will put in a comment at the part that is not working)
import java.io.File;
import java.util.*;
public class Problem9 {
/**
* @param args
*/
public static void main(String[] args) {
File rf = new File("RandomFloats");
Scanner kb = new Scanner(rf); //Unhandled exception type
FileNotFoundException
double[] numFloats = new double [4268];
for (int i = 0; i < numFloats.length; i++){
numFloats[i] = kb.nextInt();
}
System.out.println("Please enter a file name");
String fileName = kb.nextLine();
minValue (numFloats);
maxValue (numFloats);
totalValue (numFloats);
averageValue (numFloats);
}
public static void minValue (double[] numFloats){
double min = 0;
for(int i = 0; i < numFloats.length; i++){
if (numFloats[i] < min){
min = numFloats[i];
}
}
System.out.println("Min Value: " + min);
}
public static void maxValue (double[] numFloats){
double max = 0;
for(int i = 0; i < numFloats.length; i++){
if (numFloats[i] > max){
max = numFloats[i];
}
}
System.out.println("Max Value: " + max);
}
public static void totalValue (double[] numFloats){
double total = 0;
for (int i = 0; i < numFloats.length; i++){
total += numFloats[i];
}
System.out.printf("\nTotal1: %.1f" , total);
}
public static void averageValue (double[] numFloats){
double total = 0;
double average;
for (int i = 0; i < numFloats.length; i++){
total += numFloats[i];
}
average = total / numFloats.length;
System.out.printf("\nAverage: %.1f" , average);
}
}
I am unsure how to print out the sample size and the file RandomFloats I
created isnt being read into the array. Please help me I am completely
stuck, Thanks!!

No comments:

Post a Comment