Modifying function fails to print expected result
Chao, I would like to modif开发者_StackOverflow中文版y a variable then get its value after the modifying function but why I get unexpected result.
String value="I miss the messenger";
public void func(String value)
{
value.replace("miss","kiss");
}
/// print it
Writeline(value);
Thank you
The string you pass isn't modified (Strings are immutable in Java).
Thus the replace(...)
method will return a modified version of the original string, which you will have to pass around, otherwise it gets lost.
Change it to:
public String func(String value)
{
return value.replace("miss","kiss");
}
String value="I miss the messenger";
value = func(value);
Writeline(value);
Java strings are immutable, hence replace
creates a new string which must be assigned, e.g.,
value = value.replace("miss", "kiss");
Your function should return a string and you should printoiut what`s return
public String func(String value)
{
return value.replace("miss","kiss");
}
String value="I miss the messenger";
/// print it
Writeline(func(value));
精彩评论