0

My program terminates after taking one string input. It doesn't take string 2 input.

Here is the snippet of code:

    public static void main (String[] args) {
        Scanner scn= new Scanner(System.in);
        int T ;
        T=scn.nextInt();
        while(T!=0){
            String s1 = scn.nextLine(); // after i give input for the first string ,program terminates!
            String s2 = scn.nextLine(); // program terminates before asking for s2 input
            System.out.println(isMetaString(s1,s2));
            T--;
        }
    }
Arshad Hussain
  • 743
  • 5
  • 22
  • 2
    Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Jorn Vernee Jan 27 '18 at 11:10

2 Answers2

1
public static void main (String[] args) {
    Scanner scn= new Scanner(System.in);
    int T ;
    T=scn.nextInt();

    // scn.nextLine();  // for enter.
    // here after entering int value, 
    // you must be pressing enter,
    // that 'enter' is getting stored in s1,
    // and then when you give first string it is getting stored in s2 
    // and that is why your program is terminating.

    while(T!=0){
        String s1 = scn.nextLine(); // after i give input for the first string ,program terminates!
        String s2 = scn.nextLine(); // program terminates before asking for s2 input
        System.out.println(isMetaString(s1,s2));
        T--;
    }
}

Solution : add sca.nextLine() after sca.nextInt() It. will resolve the issue

0

T = scn.nextInt(); - with this line you assign an int value to variable T, but there is a new line character left that you didn't take care of (this it the character that you created when pressing Enter after your input. You might want to add sc.nextLine() right after this line or change:

T = scn.nextInt();

to:

T = Integer.parseInt(sc.nextLine()); This method will take care of a new line character following int assigned to T.

By the way, remember that this is good to follow Java naming conventions to keep you code easy to read for others. When naming variables use camelCase.

Przemysław Moskal
  • 3,321
  • 2
  • 8
  • 20