【问题标题】:Java function calling and return value in AndroidAndroid中的Java函数调用和返回值
【发布时间】:2014-02-22 05:07:24
【问题描述】:

我有一个 Java 类,其中包含一些要根据标志值操作的代码,下面是我的代码,它的标志值是 1

if(flag==1)
{
    Log.d("Flag value", "flag= "+flag);
    System.out.println("Read have "+read());
    String tt=read();
    s1=tt;
}

从上述函数中,变量“s1”中的值是 read() 函数返回的某个字符串值。

这段代码的输出是返回两次 read() 函数,比如

s1 有 "StringString"

这是我的读取功能代码

public String read(){

          try{
             FileInputStream fin = openFileInput(file);
             int c;

             while( (c = fin.read()) != -1)
             {
                temp = temp + Character.toString((char)c);
             }
          }
          catch(Exception e)
          {

          }
          Log.d("INSIDE READ FUNC", "temp have "+temp);
        return temp;
       }

虽然我省略了这个 "System.out.println("Read have "+read());"通过下面的代码

if(flag==1)
    {
        Log.d("Flag value", "flag= "+flag);
        //System.out.println("Read have "+read());
        String tt=read();
        s1=tt;
    }

我得到了完美的输出,比如

s1 有“字符串”

代码怎么会这样?我只调用了一次 read() 函数来存储到“tt”变量。

并将 tt 变量存储到 s1 变量中。

但是当我使用 System.out.println("Read have "+read());它调用并将返回的字符串值存储在数组中,第二次我存储到“tt”字符串变量,并将 read() 函数中最后返回的字符串附加到“tt”字符串变量。

所以“tt”字符串变量有两次read()函数返回的字符串。 它是如何存储两次的?

【问题讨论】:

  • 您可以将代码发布到 read() 方法吗?我认为这可能是值被保存并再次附加的地方。
  • 我现在更新了阅读功能,检查一下@DavidCAdams
  • 因为当你调用 read() 时,它会将当前指针跳转到下一个字符。
  • 但我只存储了一次到一个变量,对吧? @BirajZalavadia
  • 只需在 read() 方法中的 try catch 部分添加temp = "" ..

标签: java android function


【解决方案1】:
if(flag==1)
    {
        Log.d("Flag value", "flag= "+flag);
        //System.out.println("Read have "+read());
        String tt=read();
        s1=tt;
    }

在上面的代码中,read() 方法被调用了两次。而在read() 内部方法变量 "temp" 被声明为全局的,并且您正在连接数据,例如

temp = temp + Character.toString((char)c);

所以值在临时变量中连续两次。

要解决问题,请将 temp 声明为局部变量,如

public String read(){
          String temp="";
          try{
             FileInputStream fin = openFileInput(file);
             int c;

             while( (c = fin.read()) != -1)
             {
                temp = temp + Character.toString((char)c);
             }
          }
          catch(Exception e)
          {

          }
          Log.d("INSIDE READ FUNC", "temp have "+temp);
        return temp;
       }

【讨论】:

  • 哇……这正是我需要的……谢谢@Biraj
  • 在 try catch 语句上方定义 String temp。
【解决方案2】:
temp = temp + Character.toString((char)c);

您没有在 read() 方法中定义 temp,因此它可能被定义为全局变量。这意味着每次调用 read() 方法时,都会将新值附加到它。 您可能应该在您的 read() 方法中定义 temp:

String temp;

应该可以解决它。

【讨论】:

    【解决方案3】:
    InputStream is = Context.openFileInput(someFileName);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    while ((int bytesRead = is.read(b)) != -1) {
       bos.write(b, 0, bytesRead);
    }
    byte[] bytes = bos.toByteArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多