Home > Net >  Can i invoke another method inside of an argument list of another method?
Can i invoke another method inside of an argument list of another method?

Time:10-27

I get an error related to the replace method. Can i invoke another method inside of an argument list of another method?

        String str="Candy";
        String newStr = "";
        for(int i=0; i<str.length();i  ){
            newStr = str.replace(str.charAt(i),"");
        }```

CodePudding user response:

str.charAt(i) returns a char, and String#replace accepts a String as its first argument. Refactor it to

newStr = str.replace(String.valueOf(str.charAt(i)),"");

CodePudding user response:

Your problem is not related to "another method inside of an argument list of another method".

This call

 str.replace(str.charAt(i),"");

needs a method matching

 String replace(char, String);

No such method exists. There are methods matching

 String replace(char, char);
 String replace(String, String);

(Minor liberties taken in the interest of simplicity; actual methods have arguments of CharSequence rather than String, but that does not affect the answer)

  •  Tags:  
  • java
  • Related