0

I'm trying to take a list of strings and then print their reversed versions one by one. I'm inputting a number first, which indicates the number of strings in the list and then inputting the strings using a for loop.

However, this program directly prints the output of the first string without accepting the rest of the strings. Where am I going wrong?

import java.util.*;

class Trial {
    public static void main(String args[] ) throws Exception {

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        String strList[] = new String[n];

        for(int i = 0; i < strList.length; i++){
            strList[i] = sc.nextLine();
        }

        for(int i = 0; i < strList.length; i++){
            StringBuffer a = new StringBuffer(strList[i]);
            System.out.println(a.reverse());
        }

    }
}

As you can see, I gave 2 as input to take 2 strings but after accepting the first string, it is directly giving me the output.

enter image description here

vagaBond
  • 41
  • 5

1 Answers1

1

The invocation of sc.nextInt() is not reading the new line characters.

So the nextLine is reading the "not-read newline character" and puts it in the first element at index 0 of your strList.

Then you type ab which will be put at the index 1 and that's when the second loop is run.

Change the line for reading the number of elements to something like this:

int n = Integer.parseInt(sc.nextLine());
kkmazur
  • 446
  • 2
  • 6