I am coding a rainfall averaging program. The program lets the user input a file name and if the file cannot be found, then the user is prompted to reenter the file name. The user gets 4 tries before the application quits without processing the data, and the application itself is a rainfall averaging program like I said.
package experiment8;
import java.io.*;
import java.util.Scanner;
public class Exceptions
{
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 scan = new Scanner (System.in);
Scanner file = new Scanner(new File("inData.dat"));
fileOk = true;
}
catch(FileNotFoundException error)
{
System.out.println("Reenter file name>");
fileName = inName.nextLine();
fileTry++;
}
} while (!fileOk && fileTry < 4);
PrintWriter outFile = new PrintWriter(new FileWriter("outData.dat"));
if (fileOk && fileTry < 4 )
{
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();
}
}
I am trying to code this program so when I input the correct file name, "inData.dat", I will get the proper output. However, when I do this, I continue to get prompted to reenter the file name for the next 3 times, after which I get the "Error" message. Is there something wrong with my try/catch blocks or if statements?
Aucun commentaire:
Enregistrer un commentaire