With that code I get the following output "ajavaj" when I input "java" so how can I fix this? I need to switch the first two letters and still have the middle of the string. What should I do?
John Sing wrote:With that code I get the following output "ajavaj" when I input "java" so how can I fix this? I need to switch the first two letters and still have the middle of the string. What should I do?
Well, the problem is in line 14, and you clearly understand how to use substring(). So how do you think you might use it to correct the problem?
You better practice with String and StringBuilder functions first.
class name should always start with capital letter like PrintTest rather than printTest. Please read this link
John Sing wrote:public class printTest
Agreed thoroughly! will keep in mind validations and clean code like creating separate method rather than writing in main. Thank you
Paweł Baczyński wrote:It would be a great idea to write a method that would do the switching. What would this method is the string has length 0 or 1?
Ganish Patil wrote:do you mean here?
No, but you're still using StringBuilder in a very clunky way. The whole point about it is that it's mutable, so you can change any character anywhere in the "string".
Consider this:<private rant>
Aaargh! Why can't designers be consistent???!!! If setCharAt() returned the old character value - like pretty much every 'setter' in the Collections framework does - that method could have been implemented in two lines.
@Ganish: Tip: NEVER return void if your method can usefully return something else.
Isn't the reason that the StringBuilder methods return this so you can daisy‑chain the calls:-
Winston Gutkowski wrote:. . . If setCharAt() returned the old character value . . .
. . . sb.setCharAt(a, charb)..setCharAt(b, chara);
Surely you would return
and have String as the return type?