import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
// The "FileProcess2" class.
/*September 25, 2016
Programmer: Toni L
This is a program to enter in expense values from a specific text file(previously created) and sort them, then add them to get the total. Also calculates the average expense value.*/
public class FileProcess2
{
//Integer to contain number of rows in text file
static int days = 0;
static double hold = 0.00;
//Method to take the double array that contains the expense value and using a bubble sort, organize them from greatest to least then return sorted array
public static Double[] Organiser(Double[] expenses)throws FileNotFoundException, IOException {
for(int i=0 ; i<days ; i++){
for(int y=0 ; y<(days-1) ; y++){
if(expenses[y] < expenses[y+1]){
hold = expenses[y];
expenses[y] = expenses[y+1];
expenses[y+1] = hold;
}
}
}
return expenses;
}
public static void main (String[] args)throws IOException
{
//File Reader to read in the contents of the file
BufferedReader rF = new BufferedReader (new FileReader ("expenses.txt"));
//Actual number of lines in text file is generated
while(rF.readLine() != null){
days ++;
}
//Declaring string array to enter values from text file
Double expenses[] = new Double[days];
while(rF.readLine() != null)
{
}
rF.close();
//Declaring new double array to enter the values from the text file
//Runs Organiser Class
Organiser(expenses);
//Printing values in table format, with column headings.
System.out.println("Number"+"\t"+"Expenses");
for(int s = 0; s<days ; s++){
System.out.println((s+1)+"\t"+ expenses[s]);
}
}
//Calculates the total of the expenses as well as the average/
public static void totaler(double[] expenses)throws FileNotFoundException, IOException {
double hold = 0.00, total= 0.00, average= 0.00;
for(int u = 0; u<days; u++){
hold = expenses[u];
total = hold + total;
average = (total/days);
}
//Outputs the total as well as the average.
System.out.println("The total value of Shelley's purchases is: "+total);
System.out.println("The average value of Shelley's purchases is: "+ average);
}
}
When running the program, I cant seem to get it to read in the numbers from the text file properly, because it always gives me a NullPointerException
. I read the documentation for that exception, and I know that it means that my array called expenses[]
is null, but I'm not sure how to give it values. Can someone help me?