gpt4 book ai didi

Android中的Java函数调用和返回值

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:37:26 30 4
gpt4 key购买 nike

我有一个 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() 函数返回的字符串。两次存储如何?

最佳答案

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

关于Android中的Java函数调用和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21949983/

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