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

Here is my code. The goal is to enter basic information (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 problem I am facing is when the loop goes to the second variable, that is, I cannot enter a value for the name of the patient. It seems that he skips the entrance there and goes directly to the next entrance, which is a floor.

 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 this is happening? Is it better to use a BufferedReader?

+6
source share
2 answers

If you must use Scanner , always use nextLine() . The problem is that nextInt() reads only the whole part of the input and stops before reading the Enter message. Then the next call to nextLine() sees pressing Enter in the buffer and all the empty names you entered.

So you can do something like:

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

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

+7
source

If you are sure that the name will be in one word (this is not a problem for a man or woman), you can change the scanner input to just get a string;

  in.next(); 

it works fine (only if the name of one word).

0
source

Source: https://habr.com/ru/post/945905/


All Articles