I am trying to write a mile tracker program that keeps track of distance a user walks, runs, or swims. The program asks for user input of distance walked during a session, stores that in a double, reads data from a file about the total amount of distance previously walked, adds the distance from the latest session to the past total to create a new total, and writes that total to the file where it is stored for future use. When writing the code, the IDE shows errors at the print writer and Scanner when I try to point them to the file:
Scanner reader = new Scanner(storage); //error at second Scanner
PrintWriter writer = new PrintWriter(storage); // error at second PrintWriter
the error reads "FileNotFoundException"
when placed within a try block, the error goes away and instead the program prints the catch block error report when ran:
catch(FileNotFoundException e){
System.out.println("Check that the text file is in the correct directory.");
e.printStackTrace();
}
This is the first program I have written using PrintWriter, so some pointers and an explanation about what I am doing wrong would be appreciated.
Here is the full code:
import java.io.File;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.String;
public class Main {
public static void main(String[] args) {
//gets interval data from user
System.out.println("Please type the amount of miles walked.");
Scanner input = new Scanner(System.in);
double inMiles = input.nextDouble();
//creates file and scanner that reads to file
File storage = new File ("Mile Tracker//Mile.txt");
try {
storage.createNewFile();
}
catch(IOException e ){
System.out.println("File not created.");
}
try {
Scanner reader = new Scanner(storage);
//takes data from file and sets it to a variable
double Miles = reader.nextDouble();
double TotalMiles = Miles + inMiles;
//PrintWriter reader = new PrintWriter( file );
//PrintWriter that clears the file
/*PrintWriter clearwriter = new PrintWriter(storage);
clearwriter.print("");
clearwriter.close();
*/
PrintWriter writer = new PrintWriter(storage);
writer.print(TotalMiles);
writer.close();
}
catch(FileNotFoundException e){
System.out.println("Check that the text file is in the correct directory.");
e.printStackTrace();
}
}
}
If you already have a directory named "Mile Tracker", check if it is in the same path of the java class, since you are not explicitly giving the path to the File
constructor. If you do not have a "Mile Tracker" directory, then you modify the code as:
File storage = new File ("Mile Tracker//Mile.txt");
try {
storage.getParentFile().mkdirs();
storage.createNewFile();
}
catch(Exception e ){
System.out.println("File not created.");
}
From this point, the FileNotFound
error should be resolved.