Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

File not found exception in Java code?

In the following code in the while loop after the equal sign I am given the error that the file cannot be found. Since I am of course having the file read in by the user I'm not sure why it is giving me this error?

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Scanner;

public class StatDriver {

public static void main (String[] args)throws IOException

{

Scanner scan = new Scanner (System.in);

final int SIZE = 20;

int count = 0;

String fileName;

double[] grades = new double[SIZE];

Stat statistics = new Stat(grades, count);

System.out.print(" Enter file name: ");

fileName = scan.next();

readFile(fileName, grades);

System.out.println("\n My Grades - View Statistics\n -------------------------");

System.out.println(" Count: " +statistics.getCount());

System.out.println(" Average: " +statistics.calcAvg());

System.out.println(" Median: " +statistics.calcMedian());

System.out.println(" Maximum: " +statistics.findMax());

System.out.println(" Minimum: " +statistics.findMin());

}

private static void readFile(String fileName, double[] grades)

{

final int SIZE = 20;

Scanner inFile = null;

for(int i = 0; i < SIZE; i++)

{

inFile = new Scanner(new File( fileName ));

while(inFile.hasNextDouble())

{

grades[i] = inFile.nextDouble();

i++;

}

}

inFile.close();

}

}

2 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    FileNotFoundException is literally that -- the file could not be found. You can try outputting the file name to see what file you're trying to open.

    Possible ways the code could fail:

    - User types in wrong filename

    - Filename/path has a space in it

  • ?
    Lv 6
    1 decade ago

    It means it can't find the file that's being entered.

    Check the spelling, case, and path to make sure it's correct. Try inputting the full path and if that doesn't work try entering it wrapped in quotes. The full path is required if the file being entered is not in the same directory as your class file.

    If nothing works try hard coding a file you know exists and give it a try.

Still have questions? Get your answers by asking now.