Java - Error: Cannot find Symbol after Try...catch (fileContent[0])

Asked

Viewed 77 times

0

public class ShowDoMilhao {

//constructor of the class
public ShowDoMilhao()
{

}

public static void main(String[] args) throws IOException
{
    //string to hold name of txt file
    String file1 = "Facil.txt";

    ////////////////////////////////////////////////////////////
    //Storing file into an array of strings
    try {
       //creating an object (an instance of ReadFile class)
       ReadFile file = new ReadFile(file1);

       String[] fileContent = new String[file.readLines()];
       fileContent = file.OpenFile();  

    }
    catch (IOException e) {
        System.out.println(e.getMessage());
    }
    ////////////////////////////////////////////////////////////   

    System.out.println(fileContent[0]);                
}   //end of main method   
}//end of class
  • Welcome to sopt. It is difficult to help without knowing exactly your difficulty. Click on [Edit] and better formulate the question, exposing what you are not able to do.

  • fileContent does not exist outside of Try

1 answer

0


The error occurs because you are trying to access fileContent outside the try catch.

Declare the variable before to be accessible:

public class ShowDoMilhao {

    public ShowDoMilhao() {

    }

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

        String file1 = "Facil.txt";

        String[] fileContent;
        try {
            ReadFile file = new ReadFile(file1);

            fileContent = new String[file.readLines()];
            fileContent = file.OpenFile();

        }catch (IOException e) {
            System.out.println(e.getMessage());
        }

        System.out.println(fileContent[0]);
    }
}

Note that I performed variable declaration outside the try catch, without this it is visible only in the scope of try catch

  • 1

    Cool, I understood the mistake... Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.