Chandu is a bad student. Once his teacher asked him to print the reverse of a given string. He took three hours to solve it. The teacher got agitated at Chandu and asked you the same question. Can you solve it?
Input Sample Output(Plaintext Link)
public static void main(String args ) throws Exception
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; ++i)
String input = sc.next();
int len = input.length();
StringBuilder input1 = new StringBuilder(len);
int end = input.length()-1;
int start = 0;
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.