我的代码产生了意外的结果。看来我的for循环跳过了第一次迭代,我不明白为什么。
public static void main(String[] args) { Scanner get = new Scanner(System.in); int number; // Ex.1. String family_name; String[] family_array; System.out.println("Enter number of family members: "); number = get.nextInt(); family_array = new String[number]; for(int i = 0; i < number; i++){ System.out.println("Enter family member name: "); family_name = get.nextLine(); family_array[i] = family_name; } for(int i = 0; i < number; i++){ System.out.println(family_array[i]); } }
返回…(假设输入的数字是姓名)
Enter number of family members: 5 Enter family member name: Enter family member name: 1 Enter family member name: 2 Enter family member name: 3 Enter family member name: 4 1 2 3 4
为什么第一个get.nextLine()被跳过?
当前,您对Scanner#nextInt的调用不占用换行符,因此将其传递给您的第一次调用Scanner#nextLine,因此 不会 阻塞。
Scanner#nextLine
您将需要添加
get.nextLine();
通话后nextInt,您的第一个通话nextLine将阻止IO。
nextInt
nextLine
IO