1

My program is to accept words (given as number of test cases) and print them out in reversed order. The problem is that whatever input of array size I may give, it only accepts just one word (and rest as blank). Can anyone help me figure out why? Here's the code:

import java.util.*;
public class terrible {
    public static void main(String args[]){
        Scanner input  = new Scanner(System.in);
        int test = input.nextInt();
        while(test>0){
            String str = input.nextLine();char c[] = str.toCharArray();
            for(int i=0;i<str.length();i++){
                System.out.print(c[str.length()-i-1]);
            }
            System.out.println();
            test--;
        }

    }
}
Aastik
  • 43
  • 1
  • 4
  • I executed your code. Let say I put 3 for the no of test cases then it accepts 2 cases. can u add some input and output? – Damith Ganegoda Jan 19 '16 at 10:56
  • for me, too. The problem when you type 3 and you can only type 2 is subscripe here: http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods – pL4Gu33 Jan 19 '16 at 11:06
  • I don't see any issue with your code. Executing it and providing the string "salut comment ça va" gave the output "av aç tnemmoc tulas". Indeed there is a bug when specifying the number of iteration (it iterates n-1 times) but is it your issue? – spi Jan 19 '16 at 11:07
  • I added an input.nextLine() line after nextInt() to consume last newline character. It still seems to be taking just one string input irrespective of specified test cases. – Aastik Jan 19 '16 at 17:08

1 Answers1

0

Certain versions of Java don't let you take an int and then a string as input from the same Scanner. You can create another Scanner, like

Scanner input2 = new Scanner(System.in);

and then do

String str = input2.nextLine();

djebeeb
  • 171
  • 4