-1

I have a method that reads a file then passes the values to a constructor called point. There is another class called Track that is a collection of points to show a journey.

The method to read file is not throwing a file not found an exception and I'm unsure why. I have tried a try-catch method unsuccessfully and help to get the exception to work on insight on why it's not would be appreciated.

public static void readFile(String filename)
  throws FileNotFoundException {
    int i = 0;
    ArrayList<String> textFile = new ArrayList<>();
    Scanner input = new Scanner(System.in);
    File file = new File(input.nextLine());
    input = new Scanner(filename);
    while (input.hasNext()) {
      String letter = input.next();
      textFile.add(i, letter);
      i++;
    }
    input.close();
    for (int j = 1; j < textFile.size(); j++) {
      ZonedDateTime times;
      double longitude = 0;
      double latitude;
      double elevation;
      String s = textFile.get(j);
      String[] half = s.split(",", 4);
      times = ZonedDateTime.parse(half[0]);
      longitude = Double.parseDouble((half[1]));
      latitude = Double.parseDouble((half[2]));
      elevation = Double.parseDouble((half[3]));
      Point point = new Point(times, longitude, latitude, elevation);
      add(point);
    } 
Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Aimee Boyle
  • 11
  • 1
  • 4

2 Answers2

2

You are constructing your Scanner object from a string meaning it will only scan that string (the file name), change it to

 input = new Scanner(file);

and you will use a constructor that throws a FileNotFoundException

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0

From Java documentation:

public Scanner(String source)

Constructs a new Scanner that produces values scanned from the specified string.

Parameters:

source - A string to scan

This method doesn't accept a filename as a parameter and doesn't throw a FileNotFoundException.

Try to use:

public Scanner(File source) throws FileNotFoundException

Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.

Parameters: source - A file to be scanned

Throws: FileNotFoundException - if source is not found

Diego Marin Santos
  • 1,923
  • 2
  • 15
  • 29