r/codehs • u/L_russ28 • Sep 13 '22
Basic Java. 3.8.14: Replace Letter
Hello! I’ve been struggling with getting my loop right for this problem and I was wondering if I could get some suggestions. Thank you in advance :)
9
Upvotes
1
u/L_russ28 Sep 13 '22
Hello! I’ve been struggling with getting my loop right for this problem and I was wondering if I could get some suggestions. Thank you in advance :)
2
u/troglodyte404 Sep 13 '22
Hello! Basically you want to replace the letter with what’s called in the method. So instead of tailoring the for loop to only replace l with y, you have to call the method with
replaceletter(“hello”, “l”, “y”);
Then in the loop you have to change it so it works with any letter.
1
u/4215-5h00732 Sep 13 '22
Just call String.replaceAll in your method.
1
u/Safety__Dad Sep 13 '22
Hey other people are telling to use a function but not helping you with your actual code.
On line 8 you define char c as ‘l’ this means it’s always going to fail the conditional that comes right after. You want to use the iterative value i instead.
1
u/Sufficient_Ant_3008 Sep 14 '22
You will loop the length of the string, then your loop will have a validation if else that changes the letter.
1
u/rmstart Sep 14 '22
Replace string to character array. loop through it and replace the character by comparison. Return the array as string.
1
u/FantasticMrWow Sep 14 '22
Because of the way string pools work, you do not want to do a direct comparison of strings e.g. I =="foo" but instead use the .equals() so I.equals("foo"). This is because the first one will literally check if it is the same referenced string in the string pool where as the second one will perform a proper comparison of the string values, not the string object itself
1
u/lolol29848 Aug 22 '23
this is a very easy one, instead of using the raw letters you have to use the variable "letterToReplace" to compare what to replace and the variable "replacingLetter" as the replacer!