0

In the code below, in the first iteration of the first for loop, boxes[a] is automatically assigned a null value.

The remainder of the iterations are fine (user input is accepted). Only the first has the issue where a null value is automatically assigned.

Does anyone know why this may be? Thank you.

package testing;

import java.util.Scanner;


public class Testing {


public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    Scanner in2 = new Scanner(System.in);

    int boxNumber;

    boxNumber = in.nextInt();
    String[] boxes = new String[boxNumber];

    System.out.println(boxNumber);

    for(int a=0; a <= boxes.length - 1; a++){

        boxes[a] = in.nextLine();
        System.out.println(boxes[a]);
    }

    int packageNumber;

   packageNumber = in2.nextInt();
   String[] packages = new String[packageNumber];

   System.out.println(packageNumber);

   for(int n=0; n <= packageNumber - 1; n++){

        packages[n] = in.nextLine();
        System.out.println(packages[n]);

    }

}

}
user2938543
  • 301
  • 1
  • 5
  • 12
  • 1
    Add `in.nextLine();` after `in.nextInt()` to consume the `'\n'`. Same for `in2.nextInt()`. That will work after (also why using two scanners?). – Alexis C. Jan 17 '14 at 22:08
  • possible duplicate of [Java calculator not executing if-statement](http://stackoverflow.com/questions/21177801/java-calculator-not-executing-if-statement) or actually [using scanner nextline](http://stackoverflow.com/questions/5032356/using-scanner-nextline) – Brian Roach Jan 17 '14 at 22:09
  • Also get rid of 2nd Scanner object (`in2`). It's not needed and under certain conditions could become harmful. – PM 77-1 Jan 17 '14 at 22:11

2 Answers2

1

The scenario fitting the description of what occurs is when you type in a number on the first line, then the rest of the lines are strings for the boxes.

But the nextInt() method doesn't advance past the first newline character, so the first time you call nextLine(), it matches on the rest of the line until the first newline character, "" ( not null).

After the call to nextInt(), insert a call to newLine() before the for loop to bypass the first newline character.

String firstNewLine = in.nextLine();
for(int a=0; a <= boxes.length - 1; a++){
rgettman
  • 167,281
  • 27
  • 248
  • 326
0

when you did hit enter after entring the first number you also have and empty line that's why nextLine() return empty string, you can use this boxNumber = in2.nextInt(); instead but I would suggest to think of another way, normally you don't need two Scanner instances

iouardi
  • 76
  • 1