A couple of things will help you get the most of your experience here.
1. TellTheDetails(←click). If you make it clear exactly what you're having trouble with, people will have a better chance of being able to give you the help you need.
2. When posting code, UseCodeTags(←click) to make it more readable. I've added them to your original post for you.
Zaft kossowski wrote:Thanks for the comments; I will make sure to follow your suggestions.
But, as yet, you haven't. What is the problem? Does the method work? If not, what does it return?
However, just a logical note for you. In your original post
you wrote:"I can only use the charAt() and length() methods from the String class"
yet your method contains:
Surely that violates the rules?
There is also a “replace” method for Strings. That might help.
If you have been restricted to length and charAt, you can still use those methods in combination to create and populate a char.
@Winston Gutkowski - Thank you for pointing out the error of method usage in my posted code; it is the case that I am restricted to only the charAt() and length () methods.
The purpose of the exercise was to write a function that input a String and two characters, and then replaced all occurrences of the first character with the second character, while being restricted to only use of the charAt()/length() methods in the String class. I eventually figured out a solution to the question and realized what I was doing wrong. I was not declaring an equality statement inside the body of the if and else statements; instead, I was declaring the equality statement in the return statement.
See below for solution code, which inputs a String and two characters then replaces all instances of the first character with the second:
I appreciate everyones patience and comments!
Campbell Ritchie wrote:That code has the major problem that you are repeatedly using the + operator in separate lines. It is efficient to use + on Strings many times in one line, but not in several lines, nor in one line called many times.
Of course premature optimisation is the root of all evil so you should only worry about this if you can identify this code as the cause of an unacceptable performance bottleneck. Code clarity is much more important - although appending the chars to a StringBuilder (the solution to the problem Campbell pointed out) would not reduce clarity that much.
If you have a 27‑letter String, the performance overhead will be a few μs, so you probably won’t notice it. But in this sort of code, you can sit there watching it chunter away to itself…whereas this sort of thing completes in a fraction of a second:-
Campbell Ritchie wrote:An alternative would be to go back to the char...
@Zaft: And that might be the best of all, since you can easily create a String from a char (I presume there are no rules about which String constructors you can use), viz, using your own code as a basis: