0

Here I put a 4 value in the variable length. I'm supposed to get an array with 4 elements, but I can only input 3 elements.

public static void main(String[] args) {
    int length;
    Scanner input = new Scanner(System.in);
    System.out.print("Length: ");
    length = input.nextInt();
    String[] my_friend_names = new String[length];
    for (int i = 0; i < length; i++) {
        my_friend_names[i] = input.nextLine();
    }
    for (int i = 0; i < length; i++) {
        System.out.println("Name: " + my_friend_names[i]);
    }
}

OUTPUT:

  • Length: 4
  • 1
  • 2
  • 3
  • Name:
  • Name: 1
  • Name: 2
  • Name: 3

Now if I change the length variable for a number 4, it works!

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String[] my_friend_names = new String[4];
    for (int i = 0; i < 4; i++) {
        my_friend_names[i] = input.nextLine();
    }
    for (int i = 0; i < 4; i++) {
        System.out.println("Name: " + my_friend_names[i]);
    }
}

OUTPUT:

  • 1
  • 2
  • 3
  • 4
  • Name: 1
  • Name: 2
  • Name: 3
  • Name: 4

Do you know why that is?

Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
Cesar
  • 9
  • 1
  • Does this answer your question? [Can't use Scanner.nextInt() and Scanner.nextLine() together](https://stackoverflow.com/questions/23036062/cant-use-scanner-nextint-and-scanner-nextline-together) – Mr. Jain Jul 05 '20 at 06:56

2 Answers2

2

This is because of incorrect use of the scanner api. In the first example, when you used input.nextInt(); it only read the integer part of that line, the new line char is still not used by the scanner. Later when you call scanner.nextLine() it returns the chars after 4 which was your input and the new line which is an empty string.

This question has been answered before

Scanner is skipping nextLine() after using next() or nextFoo()?

Can't use Scanner.nextInt() and Scanner.nextLine() together

Shishya
  • 979
  • 13
  • 22
  • mmm when I called the scanner.nextLine() I input a 4 value in the variable "length" (so I'm declaring 4 elements in the array), then after that, I'm supposed to input 4 elements in the array but I'm only able to input 3 elements in the array, not 4. And when I print it gives me 4 arrays but one empty. still not sure why this is happening and how can I make it work with the variable "length" and still have the same results as my second example. Thank you for your answer – Cesar Jul 05 '20 at 04:37
  • ok I understand now. When i press enter the scanner.nextLine() reads my enter input and that's why it was skipping one of my array inputs. So now I have to add an extra scanner.nextLine() just for the enter input. this is what i wrote now and it works: Scanner input = new Scanner(System.in); System.out.print("Length: "); length = input.nextInt(); input.nextLine(); – Cesar Jul 05 '20 at 04:51
-1

Java arrays are fixed. Try using a List instead.

Rod Talingting
  • 465
  • 3
  • 14