0

I was trying to reverse the String using pre-defined method reverse() which is available in StringBuffer I took input from the user and while printing the reverse string I used toString() method to avoid an extra space

import java.util.*;

public class Small {

    public static void main(String a[])
    {
    int num;

    Scanner sc=new Scanner(System.in);

    num = sc.nextInt();

    while(num>0)
    {
       String t;

           t=sc.nextLine();

       StringBuffer sb=new StringBuffer(t);

        sb.reverse();

       System.out.println(sb.toString());

     num--;  
        }
    }
}

Input:

   2
   hello
   welcome

Output:

<Empty line>
olleh

Can anyone please advise why this blank space is coming and also not getting second output?

Andy Turner
  • 122,430
  • 10
  • 138
  • 216
saurabh
  • 45
  • 1
  • 5

1 Answers1

1

sc.nextInt() doesn't consume the newline at the end of the line containing the number.

Add sc.nextLine(); after it:

num = sc.nextInt();
sc.nextLine();
Andy Turner
  • 122,430
  • 10
  • 138
  • 216