当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Why an empty space is stored in the first cell of Array?

问题描述:

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.

      int numberOfLines = in.nextInt();

      String[] lines = new String[numberOfLines];      

      in.nextLine(); // add this
      for( int i = 0; i < numberOfLines; i++ ){
          lines[i] = in.nextLine();            
      }

      for( int i = 0; i < numberOfLines; i++ ){
          System.out.println(lines[i]);
      }
网友答案:

Below code will work for you.

int numberOfLines = in.nextInt();
in.nextLine(); //Add this.

in.nextInt(); reads the integer value and then you click enter which is read by in.nextLine();

网友答案:

The relevant code is

// this reads a number, not the new line after the number
int numberOfLines = in.nextInt();
// reads the rest of the first line you typed.
lines[i] = in.nextLine(); 

If you want to ignore the rest of the line after the number, add in.nextLine();

网友答案:

You can use nextLine() instead of int numberOfLines = in.nextInt();

网友答案:

I guess it's because method nextInt() reads only the number (3) and the newline that follows is picked up by the first call to nextLine().

分享给朋友:
您可能感兴趣的文章:
随机阅读: