1

I used Java and I tried to write program that reads a number of patients and then let the employee enter their names and ages.

and I want the program reads full name such as (Maha Saeed) so I wrote the code like this but I don't know why it does not work

name = scan.nextLine();

and this is the full code

import java.util.*;

public class Answer1
{
static Scanner scan = new Scanner (System.in);
public static void main (String[] args)
{

int age ; 
int PatientNumber ;
int PatientNO;
String name ;


System.out.print("Enter number of patients :");

PatientNumber =  scan.nextInt();
PatientNO = 1;

while ( PatientNO <= PatientNumber)
{
System.out.println("Patient #" +PatientNO);
System.out.print("Enter patient's Name: ");
name = scan.nextLine(); //<- here is the problem if I write scan.next it works but it reads only the first name

System.out.print("Enter patient's Age: ");
age= scan.nextInt();
PatientNO = PatientNO + 1;
}

}
}

thanks all

anubhava
  • 664,788
  • 59
  • 469
  • 547
user2849967
  • 101
  • 1
  • 2
  • 7
  • 3
    "Does not work" is not a useful problem description. Doesn't work **how**? What happens instead of what you want? Where do you see in the documentation that it should do something else? – T.J. Crowder Oct 12 '13 at 14:46

1 Answers1

10

See Why can't I enter a string in Scanner(System.in), when calling nextLine()-method? and Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Simple solution, you can consume the \n character:

scan.nextLine();
name = scan.nextLine();
Community
  • 1
  • 1