Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Skipping a line when reading user input into an array (for loop)

Here's my code - The objective is to enter some basic info (age, name, gender) for x number of patients.

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

The issue I'm having is when the loop goes to the 2nd variable, i.e. I'm not able to enter a value for the name of the patient. It seems to skip taking the input there and goes directly to the next input, which is gender.

Enter name of patient 1
Mark
Enter gender (male/female) of patient 1
Male
Enter age of patient 1
34
Enter name of patient 2 //Skipped. Could not enter input here
Enter gender (male/female) of patient 2
Jenna

Any idea why that happens? Is it better to use BufferedReader instead?

like image 644
JPwire Avatar asked May 27 '13 03:05

JPwire


1 Answers

If you must use Scanner, then always use nextLine(). The problem is that nextInt() reads only the integer part of the input and stops before it reads the Enter keypress. Then the next call to nextLine() sees the Enter keypress in the buffer and things you entered an empty name.

So you can do something like:

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

and be prepared to handle the exception that will happen if the user types something other than a number.

like image 170
Greg Hewgill Avatar answered Oct 17 '22 04:10

Greg Hewgill