所以我有这堂课
public static String ip (String url){
try {
String webPagea = url;
URL urla = new URL(webPagea);
URLConnection urlConnectiona = urla.openConnection();
InputStream isa = urlConnectiona.getInputStream();
InputStreamReader isra = new InputStreamReader(isa);
int numCharsReada;
char[] charArraya = new char[1024];
StringBuffer sba = new StringBuffer();
while ((numCharsReada = isra.read(charArraya)) > 0) {
sba.append(charArraya, 0, numCharsReada);
}
String resulta = sba.toString();
return resulta;
} catch (Exception e)
{
}
**(compile error)
}
并且我希望上面的代码在从另一个类(如下所示)中调用时返回resulta字符串:
private class t1 implements Runnable{
public void run() {
String getip= ip("http://google.com");
}
但是我遇到编译错误,没有在两颗星所在的位置上方添加返回语句。
通常,当我在上面的try catch中定义一个字符串时,我无法在try / catch之外访问它,这是我做错了什么?
示例:
public void haha(String data)
{
try {
string test="test6";
} catch (Exception e)
}
string vv=test; <--test cannot be found
}
我想强调一点,我想获取页面的输出而不是源代码
如果网站输出文本,我只需要文本而不是html代码
欢呼
答案 0 :(得分:1)
字符串resulta
的范围在try
块的范围内。修改您的rcode,以在resulta
块外部声明字符串try
,如下所示:
public static String ip (String url){
String resulta = "";
try {
String webPagea = url;
URL urla = new URL(webPagea);
URLConnection urlConnectiona = urla.openConnection();
InputStream isa = urlConnectiona.getInputStream();
InputStreamReader isra = new InputStreamReader(isa);
int numCharsReada;
char[] charArraya = new char[1024];
StringBuffer sba = new StringBuffer();
while ((numCharsReada = isra.read(charArraya)) > 0) {
sba.append(charArraya, 0, numCharsReada);
}
resulta = sba.toString();
} catch (Exception e) {
}
return resulta;
}