0

Why is my while loop making two passes before allowing user input? Tried the same with for loop and can't figure out why it's asks for input twice before allowing user to enter input. I know it's a stupid, simple logic mistake I'm making but I'm a noob. Thanks in advance.

public static void main (String [] args){

    Scanner scan = new Scanner(System.in);

    System.out.println("How large would you like the array to be? (number)");
    int arraySize = scan.nextInt();
    String [] myArray = new String [arraySize];
    int i = 0;

    if (arraySize <= 0 ) {
        System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
    } else {
        while (i < myArray.length) {
            System.out.println("Please type a string to be entered in the array");
            myArray[i] = scan.nextLine();
            i++;
        }
    }


}

Output looks like

How large would you like the array to be? (number)
5
Please type a string to be entered in the array
Please type a string to be entered in the array
M A
  • 71,713
  • 13
  • 134
  • 174
plooms
  • 93
  • 2
  • 11

2 Answers2

4

Add scan.nextLine(); right after your nextInt:

int arraySize = scan.nextInt();
scan.nextLine();

The first iteration of the while loop is not blocking on the nextLine() because it is picking the new line after the first integer that you input.

M A
  • 71,713
  • 13
  • 134
  • 174
2

Try this:

public static void main (String [] args){

    Scanner scan = new Scanner(System.in);

    System.out.println("How large would you like the array to be? (number)");
    int arraySize = scan.nextInt();
    scan.nextLine(); // This advances the Scanner to the next line.
    String [] myArray = new String [arraySize];
    int i = 0;

    if (arraySize <= 0 ) {
        System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
    } else {
        while (i < myArray.length) {
            System.out.println("Please type a string to be entered in the array");
            myArray[i] = scan.nextLine();
            i++;
        }
    }


}
simeg
  • 1,889
  • 2
  • 26
  • 34