gpt4 book ai didi

java - 类型不匹配 : cannot convert from StringBuilder to String

转载 作者:IT老高 更新时间:2023-10-28 21:17:49 24 4
gpt4 key购买 nike

此方法返回给定 URL 的来源。

private static String getUrlSource(String url) {
try {
URL localUrl = null;
localUrl = new URL(url);
URLConnection conn = localUrl.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
String html;
StringBuilder ma = new StringBuilder();
while ((line = reader.readLine()) != null) {
ma.append(line);
}
return ma;
} catch (Exception e) {
Log.e("ERR",e.getMessage());
}
}

它给了我这个错误:

Type mismatch: cannot convert from StringBuilder to String

还有两个选择:

  1. 将返回类型改为StringBuilder。但我希望它返回一个字符串。
  2. 将ma的类型改为String。更改后的 String 没有 append() 方法。

最佳答案

随便用

return ma.toString();

而不是

return ma;

ma.toString()返回 StringBuilder 的字符串表示形式。

StringBuilder#toString()了解详情

正如 Valeri Atamaniouk 在评论中所建议的,您还应该在 catch 中返回一些内容。 block ,否则您将收到 missing return statement 的编译器错误,所以编辑

} catch (Exception e) {
Log.e("ERR",e.getMessage());
}

} catch (Exception e) {
Log.e("ERR",e.getMessage());
return null; //or maybe return another string
}

会是个好主意。


编辑

正如 Esailija 所建议的,我们在这段代码中有三个反模式

} catch (Exception e) {           //You should catch the specific exception
Log.e("ERR",e.getMessage()); //Don't log the exception, throw it and let the caller handle it
return null; //Don't return null if it is unnecessary
}

所以我认为最好做这样的事情:

private static String getUrlSource(String url) throws MalformedURLException, IOException {
URL localUrl = null;
localUrl = new URL(url);
URLConnection conn = localUrl.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
String html;
StringBuilder ma = new StringBuilder();
while ((line = reader.readLine()) != null) {
ma.append(line);
}
return ma.toString();
}

然后,当你调用它时:

try {
String urlSource = getUrlSource("http://www.google.com");
//process your url source
} catch (MalformedURLException ex) {
//your url is wrong, do some stuff here
} catch (IOException ex) {
//I/O operations were interrupted, do some stuff here
}

查看这些链接以获取有关 Java 反模式的更多详细信息:

关于java - 类型不匹配 : cannot convert from StringBuilder to String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com