Scanner 获取用户输入的整数,然后获取字符串数组,但跳过第一个输入的字符串

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

我正在使用 Scanner 对象来获取用户输入。 Scanner 首先取一个整数 'num'。然后,我创建了一个大小为 'num' 的字符串数组,并用同一扫描器通过 for 循环获取的字符串填充该数组。我的问题是,当获取第一个字符串值时,扫描仪似乎通过为它分配一个空字符串来 'skip' 它。为什么要这样做?

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();
        }
    
    }
}

这是当此程序为 运行:

时的示例输出
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

到目前为止我尝试过的:

您只需要在 scan.nextInt() 之后添加 scan.nextLine() 因为 Scanner.nextInt 方法不会读取您输入的换行符所以在阅读该换行符后调用 Scanner.nextLine returns。

在 Scanner.next() 或任何 Scanner.nextFoo 方法(nextLine 本身除外)之后使用 Scanner.nextLine 时,您会遇到类似的行为

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();
        }

    }
}