Search code examples
javaarraysjava.util.scannerprimitive-types

Scanner takes user-inputted integer, then takes array of Strings, but skips first String inputted


I am using a Scanner object to take user input. The Scanner first takes an integer called 'num'. I then create an array of Strings of size 'num' and I fill this array with Strings taken in by the same Scanner via a for-loop. My problem is that when taking the first String value, the Scanner seems to 'skip' it by assigning it an empty String. Why is it doing this?

import java.util.Scanner;

public class KrisKindle {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
    
        System.out.println("How many people are there?");
        int num = scan.nextInt();
    
        String[] names = new String[num];
    
        for(int i = 0; i < names.length; i++) {
            System.out.println("Enter name of person " + (i +1) + "/" + num);
            names[i] = scan.nextLine();
        }
    
    }
}

Here's a sample output for when this program is run:

How many people are there?
7
Enter name of person 1/7
Enter name of person 2/7
Adam
Enter name of person 3/7
Eve
Enter name of person 4/7

What I have tried so far:

  • Creating a separate Scanner object for taking my array of Strings. This causes a separate error that I can share if it might help
  • Printing the value of name 1/7 (it is empty)

Solution

  • You just need to add scan.nextLine() after scan.nextInt() because the Scanner.nextInt method doesn't read the newline character in your input created by hitting "Enter" and so the call to Scanner.nextLine returns after reading that newline.

    You will encounter a similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself)

    public class KrisKindle {
        public static void main(String[] args) {
    
            Scanner scan = new Scanner(System.in);
    
            System.out.println("How many people are there?");
            int num = scan.nextInt();
            scan.nextLine();  // This line you have to add (It consumes the \n character)
            String[] names = new String[num];
    
            for(int i = 0; i < names.length; i++) {
                System.out.println("Enter name of person " + (i +1) + "/" + num);
                names[i] = scan.nextLine();
            }
    
        }
    }