这总是让我头疼。我正在尝试在 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());
}
这是我的控制台输入和输出的样子:
输入患者信息:
姓名:约翰·多伊
疾病:髋部骨折
优先级:6
预定进入 1 号手术室的患者名单
患者: 疾病: 髋部骨折 优先级: 6
//结束控制台输出。
请注意,它没有记录我为“Name”输入的值,并且在获取“Malady”后提示需要额外输入一行(需要我再次按 Enter 键才能让它要求下一个输入) ,“优先级”)。
我已阅读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();
虽然我仍然对这个愚蠢的扫描仪的工作原理感到困惑=/
最佳答案
我相信它应该适用于:
// read patient info
System.out.println("Name: ");
String name = input.nextLine();
System.out.println("Malady: ");
String malady = input.nextLine();
System.out.println("Priority: ");
int priority = input.nextInt();
也许问题出在 Patient 构造函数之类的地方?
关于java - 如何读取 while 循环内带有空格的字符串 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13521582/