Array values do not update

bkapbkap :

I am trying to use the string after I passed it through my cleanUp function. When I return the arguments it no longer keeps the same value.

My initial strings have punctuations. I pass the strings to a method to clean up the punctuations. I return the modified strings back to my main method. I print out the modified string but my results have returned to the original value of the string.

public class test{

    public static void main(String[] args){

        String str1 = "this-is.first:sentence/.";
        String str2 = "this=is.second:sentece.";

        String[] arr = cleanUp(str1, str2);

        for (String string : arr){
            System.out.println("string after cleanup()" + string);
        }
    }

    public static String[] cleanUp(String str1, String str2) {
        String[] arr = {str1, str2};
        for (String string : arr){
            string = string.replaceAll("\\p{Punct}","");
            System.out.println("string cleaned:" + string);
        }
        return new String[] {str1, str2};
    }

}

Current Output:

string cleaned: this is first sentence  
string cleaned: this is second sentece 
string after cleanup(): this-is.first:sentence/.
string after cleanup(): this=is.second:sentece.

Expected Output:

string cleaned: this is first sentence  
string cleaned: this is second sentece 
string after cleanup(): this is first sentence
string after cleanup(): this is second sentece
Zabuza :

You have two issues in your code which have to do with the fact that Java is pass-by-value.

  1. You are re-assigning your local string variable in the loop, not what is inside the array. So string has the correct value, the string in array still has the old value.
  2. Your output is build out of string1 and string2 which you did never update. Your updated content is supposed to be in the arr array you built using your loop. So you must either update the values based on the arrays content or return the arrays content or directly the array

Here is a fixed version:

public static String[] cleanUp(String str1, String str2) {
    String[] arr = { str1, str2 };
    for (int i = 0; i < arr.length; i++) {
        arr[i] = arr[i].replaceAll("\\p{Punct}", "");
        System.out.println("string cleaned:" + arr[i]);
    }
    return arr;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148446&siteId=1