-1

Why usage of nextLine() is not efficiently takes the input? If i use next() instead of nextLine() the code is super good but why? whats the reason behind it.Where and all i should use next and nextLine();

import java.util.Scanner;

public class Sample{
    public static void main(String args[]) {
        String a,b;

        Scanner scan = new Scanner(System.in);
        q = scan.nextInt();
        for(int m=0;m<q;m++) {
            a = scan.nextLine();
            b = scan.nextLine();
            System.out.println(a + "" + b);
            }

    }
}

Expected:

2
mnopm
nop
mnop nop
abcdee
bee
abcdee bee

Actual:

2
mnop
mnop(output appears before taking the 2nd input)
abcee
bee
abcee bee
Devi
  • 25
  • 2
  • Is it given two Strings equals or one String contains another? Question is unclear – Sandeepa Dec 23 '18 at 07:19
  • question is to find whether String 1 == String 2 – Devi Dec 23 '18 at 07:31
  • Why do you ask for a number first to determine how many times to run. Remove that functionality and focus on the problem you are supposed to solve. Any functionality like that can be added afterwards when your core logic is working as expected – Joakim Danielson Dec 23 '18 at 07:48
  • @JoakimDanielson Agreed. It would have been easier if he just said the code is skipping the second input. Took me a while to see what was his real question – Sandeepa Dec 23 '18 at 07:58

1 Answers1

1

Replace q = scan.nextInt(); with q = Integer.valueOf(scan.nextLine()); This will do the trick

The Scanner.nextInt() method does not read the newline character in your input created by hitting enter. Please refer this link for more info

Sandeepa
  • 2,522
  • 3
  • 14
  • 34