这总是让我头疼。我正在尝试在 while 循环中读取和保存字段“名称”和“疾病”的多字字符串。这是我的代码:
while(OR1.isFull() == false || OR2.isFull() == false)
{
// prompt for next request
System.out.println("Enter patient info:");
// read patient info
System.out.print("Name: ");
String name = input.nextLine();
input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
// store patient info
Patient patient = new Patient(name, malady, priority);
OR1.add(patient);
} // end while
System.out.println("List of patients scheduled for Operating Room 1");
while(OR1.isEmpty() == false)
{
// pop and print root
System.out.print(OR1.remove());
}
这是我的控制台输入和输出的样子:
输入患者信息:
姓名:John Doe
疾病:臀部骨折
优先级:6
安排在 1 号手术室的患者名单
患者: 疾病: 髋部骨折 优先级: 6
// 结束控制台输出。
请注意,它没有记录我为“Name”输入的值,并且在获得“Malady”后它提示输入额外的一行(要求我再次按 Enter 以获取下一个输入,“Priority ”)。
我已阅读http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html上的文档。我尝试过 next() 和 nextLine() 的不同组合。我只是不明白。
通过将代码更改为以下内容解决了问题:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
虽然我仍然对这个愚蠢的扫描仪如何工作感到困惑 =/