[Solved] Output for reversing a string does not come as expected


For approach 1, all you need to do is remove the call to sc.nextLine() and everything will be fine. That’s because each line contains a “token” i.e. a word, delimited by whitespace. That’s what sc.next() will return. No need to call nextLine() after that.

For your approach 2, you should carefully read the API documentation of StringBuilder. This shows you how to create a String from a StringBuilder, and vice versa. (Whenever I write Java code, I have a browser window with the API documentation for quick reference next to my editor window. It’s very useful.)

Edit (after the latest edit to the question):

There is a compilation problem and a runtime problem. First, the XOR operator produces a result of type int, even if its operands are char. So you should put your expression in parentheses and cast it to char. Once you’ve done that, you’ll get a runtime error because you are trying to index an element of a StringBuilder which does not yet exist. When you created the StringBuilder like this:

StringBuilder input1=new StringBuilder(len);

len is the initial capacity. The value of the StringBuilder instance is initially “”. You then call setCharAt() but the current size of the StringBuilder is 0, so you get an index-out-of-bounds exception. You need to initialise the StringBuilder with the string itself:

StringBuilder input1=new StringBuilder(input);

Now you won’t get an exception, but you’ll get the wrong answer. That’s because of a problem with your XOR logic.

solved Output for reversing a string does not come as expected