【问题标题】:Trying to return with a variable which is cannot be resolved as variable试图返回一个无法解析为变量的变量
【发布时间】:2014-06-17 08:25:19
【问题描述】:

我是 Java 新手,我试图在函数末尾返回一个已定义的字符串变量,但 eclipse 一直说它无法解析为变量,并希望我定义它。可能是因为我在 Try{} 括号内定义了变量,但我还能怎么做呢?

public class readtextfile extends AsyncTask<String, Integer, String>{

private TextView description;
public readtextfile(TextView descriptionTextView){
    this.description = descriptionTextView;
    }

@Override
protected String doInBackground(String... params) {

    try {

        URL url = new URL("http://example.com/description1.txt");       

        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = null;
        String result = "";
        while ((line = in.readLine()) != null) {
            //get lines
            result+=line;
        }
        in.close();

        } catch (MalformedURLException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    return result;

}

 protected void onProgressUpdate() {
    //called when the background task makes any progress
 }

  protected void onPreExecute() {
     //called before doInBackground() is started
 }

@Override
 protected void onPostExecute(String result) {
     this.description.setText(result); 
 }
  }

【问题讨论】:

    标签: java function variables return


    【解决方案1】:

    移动局部变量声明

      String result = "";
    

    在 try 块之前。如果您在块内定义变量,则该变量在该块外不可用。

    或者,您可以将 return result; 移到 try 块的末尾,但是您必须在方法的末尾添加另一个 return 语句,以防异常被抛出并被捕获。

    或者你可以去掉 try 块,将异常处理移到其他地方,让任何异常都被抛出。

    【讨论】:

    • 我自己不了解 Java,但从外观上看,这可能是范围问题,这就是解决方案。
    • 是的,已解决,谢谢,但是现在我正试图将字符串放入 textview,但它是空的。 txt文件没问题,我已经检查过了,代码中只是一个例子。
    【解决方案2】:
    URL url = null;
    String result = "";
    

    然后在你的 try, catch 块中。

    try {
        url = ....;
        .
        .
        result = ....;
    

    在try块外声明变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2011-11-27
      • 2012-04-14
      • 2021-11-20
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多