"error: cannot find character" in return statement

I am trying to return a variable String authServer

, but I cannot seem to do it.

public static String getAuth () {
    Connection connection = null;
    try {
        connection = ConnectionConfig.getConnection();
        if (connection != null) {
            Statement query = connection.createStatement();
            ResultSet rs = query.executeQuery("SELECT auth FROM auth");
            while (rs.next()) {
                String authServer = rs.getString("auth");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return authServer;
    }
}

      

The above code is giving me an error with unknown symbol "authServer".

What am I doing wrong?

+3


source to share


3 answers


Since it is authServer

declared in the loop above, it is not in scope when you try to use it in a return statement.

Java Made Easy has a nice overview of the variable scope in Java to help you better understand the problem.



In your specific case, consider the following modification to work around the problem:

public static String getAuth () {
    // Declare authServer with method scope, and initialize it.
    String authServer;
    Connection connection = null;
    try {
        connection = ConnectionConfig.getConnection();
        if (connection != null) {
            Statement query = connection.createStatement();
            ResultSet rs = query.executeQuery("SELECT auth FROM auth");
            while (rs.next()) {
                // Just assign to authServer here rather than declaring
                // and initializing it.
                authServer = rs.getString("auth");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return authServer;
    }
}

      

+1


source


Don't declare authServer in a while loop. It will be closed after the while loop. You must declare outside of the while loop.

public static String getAuth () {
    Connection connection = null;
    String authServer = "";
.....

      



Then get the result from the while loop.

+3


source


You declare authServer inside a while loop, making it unavailable in a return statement. Declare it after the join instruction like this:

Connection connection = null;
String authServer="";

      

And then use in a while loop like this:

while (rs.next()) {
  authServer = rs.getString("auth");
}

      

+1


source







All Articles