为什么首先跳过循环迭代? [英] Why is first for loop iteration skipped?

查看:153
本文介绍了为什么首先跳过循环迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码产生了意想不到的结果。似乎我的for循环跳过第一次迭代,我不明白为什么。

my code is yielding an unexpected result. It seems my for loop skips the first iteration and I don't understand why.

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

}

返回...(假装号码输入是姓名)

Returns... (pretend the number input are names)

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()?

Why is the first get.nextLine() skipped?

推荐答案

目前您打电话给扫描仪#nextInt 不是使用换行符,所以它被传递给你第一次调用 Scanner#nextLine ,因此它阻止。

Currently your call to Scanner#nextInt is not consuming the newline character so it is being passed through to your first call of Scanner#nextLine, therefore it does not block.

您需要添加

get.nextLine();

致电 nextInt 以便第一次通话到 nextLine 将阻止 IO

after calling nextInt so that your first call to nextLine will block for IO.

这篇关于为什么首先跳过循环迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆