0

I'm solving a programming challenge on hacker-earth, in which I've to scan a large number of space separated Strings. To scan such a String I used nextLine() method,about which I've read here. But It works only first time in the following while() loop. and after that nothing is scanned or printed in output.Here is my code:

Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t-->0){
        in.nextLine();
        String s = in.nextLine();
        String str[] = s.split(" ");

        for(int i=0;i<str.length/2;i++){
            String temp;
            temp = str[i];
            str[i] = str[str.length-i-1];
            str[str.length-i-1] = temp;
        }

        for(int i=0;i<str.length;i++){
            System.out.print(str[i]+" ");
        }    
   }

I've Input like this:

2                              //number of Strings to be Scanned.
Hello World
Hello StackOverFlow Users

For the first String Hello World, output comes perfectly fine,but nothing happens after this output. What I'm doing wrong here? Any help will be appreciated.

Community
  • 1
  • 1
  • Your loop is ending, because the counter `t` goes to zero after the second iteration. This is why nothing is happening. You can try increasing the value of `t` to a higher number, or you can allow the user to enter a special value to indicate that he wants the program to terminate. – Tim Biegeleisen Jul 05 '16 at 16:15
  • 3
    why are you using `nextLine()` twice? – dabadaba Jul 05 '16 at 16:16
  • But I've already taken the value of `t` from user –  Jul 05 '16 at 16:17
  • @dabadaba see this :: http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods# –  Jul 05 '16 at 16:19
  • but don't use it twice in the `while` loop. Use it just right after `nextInt()`, outside of the loop. I think that's why the second line is being skipped. – dabadaba Jul 05 '16 at 16:20
  • @TimBiegeleisen I've tried increasing `t` but nothing happened . –  Jul 05 '16 at 16:21
  • I don't think there's anything wrong with `t`, just try what I told you. – dabadaba Jul 05 '16 at 16:22
  • You are calling `nextLine()` twice. Stop this, and call it once. – Tim Biegeleisen Jul 05 '16 at 16:23

1 Answers1

0

As @dabadaba and @Tim Biegeleisen mentioned I removed first in.nextLine() from my code. but after that I've to increase t by 1 after user enters it. This worked for me!

Here is the correct code:

     Scanner in = new Scanner(System.in);
     int t = in.nextInt();
     t=t+1;
   while(t-->0){
          //  in.nextLine();
        String s = in.nextLine();

        String str[] = s.split(" ");

        for(int i=0;i<str.length/2;i++){
            String temp;
            temp = str[i];
            str[i] = str[str.length-i-1];
            str[str.length-i-1] = temp;
        }

        for(int i=0;i<str.length;i++){
            System.out.print(str[i]+" ");
    }

   }

Thanks for help.