0
import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] in = new String[n];
        for (int i = 0; i < n; i++) {
            in[i] = sc.nextLine();
        }
        for (int i = 0; i < n; i++) {
            System.out.println(in[i]);
        }
    }
}

Input:

2
Ankit

Output:

Ankit
EricSchaefer
  • 22,338
  • 20
  • 63
  • 99
  • 3
    Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – maloomeister Apr 20 '21 at 05:49

2 Answers2

1

That's because of the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter" and so the call to Scanner.nextLine returns after reading that newline. There are two options to resolve this issue,

1. read the input through Scanner.nextLine and convert your input to the proper format you need

    Scanner sc = new Scanner(System.in);
    int n = Integer.parseInt(sc.nextLine());
    
    String[] in = new String[n];
    
    for (int i = 0; i < n; i++)
    {
        in[i] = sc.nextLine();
    }
    
    for (int i = 0; i < n; i++)
    {
        System.out.println(in[i]);
    }

2. Add Scanner.nextLine call after each Scanner.nextInt

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.nextLine();
    
    String[] in = new String[n];
    
    for (int i = 0; i < n; i++)
    {
        in[i] = sc.nextLine();
    }
    
    for (int i = 0; i < n; i++)
    {
        System.out.println(in[i]);
    }
Pramod H G
  • 916
  • 8
  • 12
0

the Scanner class skips next line after nextint so you can fix it by editting your code like this-

import java.util.Scanner; 
public class test {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    sc.nextLine();  
    String[] in=new String[n];
    for(int i=0;i<n;i++){
        in[i]=sc.nextLine();
    }
    for(int i=0;i<n;i++){
        System.out.println(in[i]);
    }
    
    }
}