我使用Java,我尝试编写可以读取大量患者的程序,然后让员工输入他们的姓名和年龄。
我希望程序读取全名,例如(Maha Saeed),所以我写了这样的代码,但我不知道为什么它不起作用
name = scan.nextLine();
这是完整的代码
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;
}
}
}
感谢所有
答案 0 :(得分:8)
请参阅Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?和Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
简单的解决方案,您可以使用\ n字符:
scan.nextLine();
name = scan.nextLine();