I’m a java newbie looking for some help reading a file. Here is the code I am using.
source:
public void Escanear()
{
Scanner sc=new Scanner(new File("inicio.txt"));
while(sc.hasNext())
{
String token = sc.next();
if (token.equals("Pared"))
{
int i=sc.nextInt();
int j=sc.nextInt();
_mat=new Pared[i][j];
}
else if(token.equals("Fantasma"))
{
int i=sc.nextInt();
int j=sc.nextInt();
_mat=new Fantasma[i][j];
}
}
}
Error:
C:\Users\User\Documents\Jorge\Clases UNIMET\Trimestre 5\Estructuras de Datos\Proyecto Pacman\JuegoPacman.java:28: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner sc=new Scanner(new File("inicio.txt"));
I’ve imported java.io.FileNotFoundException, and I’ve already opened the .txt file, which is located in the same folder as the class I’m compiling… Any idea of how can it be fixed? THANKS.
This
error: unreported exception FileNotFoundException; must be caught or declared to be thrownis a compilation error. It means that one of the method calls in your code is declared to throw a FileNotFoundException.It is not related to the location of the file because your program doesn’t even get executed.
Scanner constructor that you call on line 28 is declared to potentially throw a FileNotFoundException.
This means that you need to handle this potentially thrown exception. Either by adding
throws FileNotFoundExceptionto your Escanear method definition (which shouldn’t start with capital letter btw), or by surrounding the line with this method call withtry-catch.