【问题标题】:"error: cannot find symbol" in Return Statement返回语句中的“错误:找不到符号”
【发布时间】:2015-08-29 04:26:17
【问题描述】:

我正在尝试返回一个变量 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”的错误。

我做错了什么?

【问题讨论】:

  • 您已经在 while 循环的上下文中声明了 authServer,使得该方法的其余部分无法访问它
  • 好的,谢谢!我现在试试

标签: java scope


【解决方案1】:

您在 while 循环中声明 authServer,使其无法在 return 语句中访问。 在连接语句之后声明它,如下所示:

Connection connection = null;
String authServer="";

然后在while循环中使用如下:

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

【讨论】:

    【解决方案2】:

    不要在 while 循环中声明 authServer。它的作用域将在 while 循环之后结束。您需要在 while 循环之外声明。

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

    然后从 while 循环中检索结果。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2013-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        相关资源
        最近更新 更多