我有一个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有” + 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” String变量中,并将最后一次从read()函数返回的字符串附加到“ tt” String变量中。
因此,具有两次read()函数的“ tt” String变量返回了String。它如何存储两次?
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);
因此,在临时变量中,值是concat的两倍。
要解决此问题,请将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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句