0

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
Sandipan Majhi
  • 104
  • 1
  • 9
  • 2
    Your call to `nextInt` leaves the newline behind. See the duplicate for more detail - the question may be kind of different, but the answer's the same. – Dawood ibn Kareem Aug 17 '19 at 05:50
  • Thanks I got it and it workded. I didn't understand that the scanner is consuming the enter I was hitting. – Sandipan Majhi Aug 17 '19 at 06:10

0 Answers0