-2

I'm getting an error on my Scanner input line, where I put (new File(myths.txt)) on the word File, it says can't find symbol class File.

package program6;
import java.util.Scanner;


public class Program6{
String[] StringArray = new String[100];
int[] IntArray = new int[100];
String FileName = "myths.txt";
Scanner input = new Scanner(new File("myths.txt"));
Dada
  • 6,313
  • 7
  • 24
  • 43
Tonno22
  • 167
  • 2
  • 10

3 Answers3

1

you have not imported class File.The class File is present in io package

import java.io.File;
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

You need to add an import statement for File class.

import java.io.File; // import statement for File.

Also you can just use the fileName to create the new File instead of giving the hardcoded name again.

String FileName = "myths.txt";
Scanner input = new Scanner(new File(FileName));

Since you're creating a new Scanner object using the new File(fileName), this constructor of Scanner throws a FileNotFoundException which needs to be handled.

I advice you move this code to a method inside the class and handle the FileNotFoundException either by having a throws clause or a try-catch around the code creating a new Scanner using a File object.

You can see an example here on how to handle a checked exception, in your case, FileNotFoundException.

Community
  • 1
  • 1
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • Why would I get an error, unreported exception FileNotFoundException; must be caught or declared to be thrown? – Tonno22 Dec 05 '13 at 07:10
  • @user2934545 see this link for checked and unchecked exception http://www.beingjavaguys.com/2013/04/exception-handling-in-java-exception.html – SpringLearner Dec 05 '13 at 07:13
  • Couldn't I just add a throws FileNotFoundException somewhere? – Tonno22 Dec 05 '13 at 07:27
  • You can add a throws clause, but for that the code needs to be in a method as only a method can have the throws clause. Even if you want to use a try-catch, it must be inside a method and not hanging around in the class. – Rahul Dec 05 '13 at 07:29
  • If you want them to be instance variables, you can just declare them there and initialize in the method or constructor handling the error in it. – Rahul Dec 05 '13 at 07:29
0

You missed imports. That's why you are getting this error. Add import to your code.

import java.io.File;
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115