Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java—将用户输入读取到数组时跳过一行(for循环)_Java_Java.util.scanner - Fatal编程技术网

Java—将用户输入读取到数组时跳过一行(for循环)

Java—将用户输入读取到数组时跳过一行(for循环),java,java.util.scanner,Java,Java.util.scanner,这是我的代码-目标是输入x个患者的一些基本信息(年龄、姓名、性别) public static void main(String[] args) { int numPatients = 2; int[] age = new int[numPatients]; String[] gender = new String[numPatients]; String[] name = new String[numPatients]; Scanner in = n

这是我的代码-目标是输入x个患者的一些基本信息(年龄、姓名、性别)

public static void main(String[] args) {

    int numPatients = 2;

    int[] age = new int[numPatients];
    String[] gender = new String[numPatients];
    String[] name = new String[numPatients];
    Scanner in = new Scanner(System.in);

    /*
     * Obtaining patients details: name, gender, age
     * First create a Scanner input variable to read the data
     */
    for (int i = 0; i < numPatients; i++)
    {
    System.out.println("Enter name of patient " + (i+1));
     name[i] =  in.nextLine();

    System.out.println("Enter gender (male/female) of patient " + (i+1));
     gender[i] =  in.nextLine();

    System.out.println("Enter age of patient " + (i+1));
     age[i] =  in.nextInt();
    }

知道为什么会这样吗?使用BufferedReader是否更好?

如果必须使用
扫描仪
,请始终使用
nextLine()
。问题是
nextInt()
只读取输入的整数部分,并在读取Enter键之前停止。然后,对
nextLine()
的下一次调用将在缓冲区中看到Enter键以及您输入的空名称

因此,您可以执行以下操作:

age[i] = Integer.parseInt(in.nextLine());

并准备好处理用户键入数字以外的内容时发生的异常。

如果您确信名称将是一个单词(不是男性或女性的问题),那么您可以修改扫描仪输入以仅获取字符串

   in.next();

这很好用(只要名字是一个单词)。

真的很有趣,我不会发现的。谢谢你的帮助,格雷格。现在可以了!
   in.next();