Harsh Rewari Harsh Rewari - 3 months ago 11
Java Question

how to keep stringbuffer constant

In my java program i have a local stringbuffer variable and i am passing that variable to another function.Now any changes in the other function is modifying the orignal variable also.How do i avoid this?please help.

the code:

main()
{
...
StringBuffer in=....
//n is the length of in
for(int j=1;j<=n/2;j++)
if(flipandcheck(in,j))
{
output=j+1;
break;
}
...
}
public static boolean flipandcheck(StringBuffer str,int index)
{
int l=1;
if(str.charAt(index)=='(')
str.setCharAt(index,')');
else
str.setCharAt(index,'(');
for(int i=1;i<str.length();i++)
{
if(str.charAt(i)=='(')l++;
else --l;
if(l<0)return false;
}
if(l==0)return true;
else return false;
}

Answer

Create a copy of the buffer and pass it.

for(int j=1;j<=n/2;j++) {
    if(flipandcheck(new StringBuffer(in),j)) {
            output=j+1;
            break;
    }
}

Then, you might want to review this question.

Comments