I am writing a program to reverse the string. I used the StringBuilder class. The problem is that when I try to run the while loop, it runs without taking the input first time.
I have tried filling in some minor changes into the code like initialising the p variable outside the while loop.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.lang.StringBuilder;
public class ReversingString {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t;
List<StringBuilder> l = new ArrayList<>();
t = s.nextInt();
String p;
while(t>0){
System.out.println(t);
StringBuilder prev = new StringBuilder();
p = s.nextLine();
prev.append(p);
prev = prev.reverse();
l.add(prev);
t--;
}
for(StringBuilder i : l)
System.out.println(i);
}
}
When I give the testcase t as 3 it runs like this....
3 // the testcase input through scanner
3 // value of testcase at this point in loop
2 // testcase value automatically decrements without taking input
sandi
1
and
idnas //output
dna