-2

I'm working on a personal project and I'm fairly new at java (trying to create a web application). I'm having some issues returning an arraylist that I've defined earlier in the method. The arraylist prints normally but for some reason my IDE is saying it's not defined when I try to return it. Here's my code, and thanks for any help:

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.mysql.jdbc.Statement;

public class Fire_Emblem {

public static ArrayList<String> GetCharacters() {

        try {
            Class.forName("com.mysql.jdbc.Driver"); 
            java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/fire_emblem","root","[redacted]");
            java.sql.Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select name from characters");
            System.out.println ("Connection successful");
            ArrayList<String> list = new ArrayList<String>();
                while (rs.next()) { 
                    list.add(rs.getString("name"));
                }
                System.out.println(list);
            }
        catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println("Connection failed");
        }
return list;
}

}

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

4

You created the list within the scope of the try block. Define it before try.

If nothing is referencing list after the program leaves the scope where it was created, then the object will be destroyed. For more on this topic look here

ArrayList<String> list = new ArrayList<String>();
try {
    ...
} 
catch (SQLException e) {
    System.out.println(e.getMessage());
    System.out.println("Connection failed");
}
return list;
flakes
  • 21,558
  • 8
  • 41
  • 88
0

The list variable is inside the try {} scope. You are referencing the list variable outside its scope.

The IDE tells you Cannot resolve symbol 'list' which means the variable is not defined in this scope.

Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71