Can some body explain why an empty space is stored in first cell of my String Array? I am trying to store each line inputted through console into a String array.

import java.util.Scanner;

public class ClassNameHere {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int numberOfLines = in.nextInt();

String[] lines = new String[numberOfLines];

for( int i = 0; i < numberOfLines; i++ ){

lines[i] = in.nextLine();

}

for( int i = 0; i < numberOfLines; i++ ){

System.out.println(lines[i]);

}

}

}

网友答案:

in.nextInt() reads only the int value not the newline character after that. So that newline will be read by your in.nextLine() so your first index is empty. To eliminate this problem add a dummy in.nextLine() after reading the int.

int numberOfLines = in.nextInt();
in.nextLine();

Another method is to use nextLine() instead of nextInt() to read the and parse the input to int.

int numberOfLines = Integer.parseInt(in.nextLine());

网友答案:

After you call in.nextInt(), the first call to in.nextLine() returns the rest of that same line, and therefore it's empty.

You should add a call to in.nextLine() before the loop to consume that empty line.