2015-06-13 54 views
3

我試圖返回一個變量String authServer,但我似乎無法做到。「返回聲明中找不到符號」

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; 
    } 
} 

上面的代碼給我一個未知符號「authServer」的錯誤。

我在做什麼錯?

+0

你while循環的範圍內聲明的authServer,使其無法訪問的方法 – MadProgrammer

+0

好的,謝謝其餘您!生病現在嘗試 – David

回答

1

由於authServer是在上面的循環中聲明的,所以它不在範圍內,當您嘗試在return語句中使用它時。

Java Made Easy擁有一個不錯的overview of variable scope in Java,它可以幫助您更好地理解問題。

在您的具體情況,請考慮以下修改來解決這個問題:

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

您在while循環中聲明authServer,使其在return語句中無法訪問。這樣的連接語句之後 聲明它:

Connection connection = null; 
String authServer=""; 

然後在while循環使用方法如下:

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

不要在while循環聲明authServer。它的作用域將在while循環後結束。你需要在while循環之外聲明。

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

然後從while循環中檢索結果。