String.replace result is ignored?

后端 未结 4 806
死守一世寂寞
死守一世寂寞 2021-01-20 13:20

So i\'m using IntelliJ and the replace buzzword is highlighted. Most of the tips are over my head so i ignore them, but what i got for this one was that the result of string

相关标签:
4条回答
  • 2021-01-20 14:03

    IntelliJ is complaining that you're calling a method whose only effect is to return a value (String.replace) but you're ignoring that value. The program isn't doing anything at the moment because you're throwing away all the work it does.

    You need to use the return value.

    There are other bugs in there too. You might be able to progress a little further if you use some of this code:

    StringBuilder convertedPhoneNumber = new StringBuilder();
    // Your loop begins here
    char curCharacter = phoneNumber.charAt(i);
    if (curCharacter == 'a') {
      convertedPhoneNumber.append("2");
    }
    // More conditional logic and rest of loop goes here.
    
    return convertedPhoneNumber.toString();
    
    0 讨论(0)
  • 2021-01-20 14:04

    String objects are immutable.

    From the docs:

    public String replace(char oldChar,char newChar)

    Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.

    Hope this helps.

    0 讨论(0)
  • 2021-01-20 14:10

    use that statement string = string.replace(string.charAt(i));

    Why? String is an immutable object. Look at this thread to get a complete explanation. This a fundemental part of Java, so make sure you learn it well.

    0 讨论(0)
  • 2021-01-20 14:26

    I had the same problem, but i did it like this:

    String newWord = oldWord.replace(oldChar,newChar); 
    
    0 讨论(0)
提交回复
热议问题