我使用Java,我尝试编写可以读取大量患者的程序,然后让员工输入他们的姓名和年龄.
我希望程序读取全名,如(Maha Saeed),所以我写了这样的代码,但我不知道为什么它不起作用
name = scan.nextLine();
Run Code Online (Sandbox Code Playgroud)
这是完整的代码
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家
请参阅调用nextLine() - 方法时,为什么我无法在Scanner(System.in)中输入字符串?和Scanner在使用next(),nextInt()或其他nextFoo()方法后跳过nextLine()
简单的解决方案,您可以使用\n字符:
scan.nextLine();
name = scan.nextLine();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8515 次 |
| 最近记录: |