I have a program that is supposed to allow the user to enter a file name, which, if correct, computes the average of the numbers within the file and prints it out. Likewise, if the user enters the wrong file name a certain number of times, then the program quits. In the program, the "try" block is supposed to instantiate the Scanner and set fileOk to true, while the "catch" block is supposed to prompt the user to reenter the file name, read the file, and increment fileTry. The first "if" statement is also supposed to make it so the average is calculated or an error message is written on the output file (outNumbers.dat). Here is the code I have so far:
package average;
import java.io.*;
import java.util.Scanner;
public class Try
{
static Scanner inFile;
public static void main(String[] args) throws IOException
{
int fileTry = 0;
String fileName;
Scanner inName = new Scanner(System.in);
System.out.println("Enter file name>");
fileName = inName.nextLine();
boolean fileOk;
do
{
fileOk = false;
try
{
Scanner file = new Scanner(new File(fileName));
fileOk = true;
}
catch(FileNotFoundException error)
{
System.out.println("Reenter file name>");
fileName = inFile.nextLine();
fileTry++;
}
} while (!fileOk && fileTry < 4);
PrintWriter outFile = new PrintWriter(new FileWriter("outNumbers.dat"));
if (fileName != null )
{
int numDays = 0;
double average;
double inches = 0.0;
double total = 0.0;
while (inFile.hasNextFloat())
{
inches = inFile.nextFloat();
total = total + inches;
outFile.println(inches);
numDays++;
}
if (numDays == 0)
System.out.println("Average cannot be computed " +
" for 0 days.");
else
{
average = total / numDays;
outFile.println("The average rainfall over " +
numDays + " days is " + average);
}
inFile.close();
}
else
System.out.println("Error");
outFile.close();
}
}
And here is the contents of the correct file(inNumbers.dat):
2.3
3.1
0.3
1.1
2.2
2.1
0.0
0.4
0.76
0.5
1.0
0.5
This is the output I get after running the program and entering the correct file name:
Enter file name>
inNumbers.dat
Exception in thread "main" java.lang.NullPointerException
at average.Try.main(Try.java:40)
I am a bit lost on how to fix this :/