Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何读取while循环中包含空格的字符串(Java)_Java_While Loop_Whitespace_Java.util.scanner - Fatal编程技术网

如何读取while循环中包含空格的字符串(Java)

如何读取while循环中包含空格的字符串(Java),java,while-loop,whitespace,java.util.scanner,Java,While Loop,Whitespace,Java.util.scanner,这总是让我头痛。我试图在一个while循环中读取并保存字段name和malady的多个单词字符串。这是我的密码: while(OR1.isFull() == false || OR2.isFull() == false) { // prompt for next request System.out.println("Enter patient info:"); // read patient info System.out.print("Name: ");

这总是让我头痛。我试图在一个while循环中读取并保存字段name和malady的多个单词字符串。这是我的密码:

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键,以使其请求下一个输入Priority

我已经在阅读了文档。我尝试了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();

问题可能出在患者构造函数中或其他地方?

通过将代码更改为以下内容来解决问题:

    // 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();

如何在类Patient中设置name?我不太确定,但input.nextLine读取缓冲区中的最后一个字符或字符串。已修复!Seee OP无法在发布后8小时内回答我自己的问题,因为我的代表太少了。