2012-11-23 115 views
1

這總是讓我頭疼。我正在嘗試在while循環中讀取並保存字段「name」和「malady」的多字字符串。這裏是我的代碼:如何在while循環中使用空格讀取字符串(Java)

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的患者名單
患者:Malady:摔斷的髖關節優先:6

//結束控制檯輸出。

請注意,它沒有記錄我爲「名稱」輸入的值,並且它在獲得「Malady」後提示輸入額外的一行輸入(要求我再次按下輸入以請求下一個輸入輸入,「優先」)。

我已閱讀文檔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(); 

雖然我仍然感到困惑這個愚蠢的掃描儀的工作原理=/

+0

你是如何設置的類''Patient' name'? – Reimeus

+0

我不太確定,但input.nextLine()讀取緩衝區上的最後一個字符或字符串。 – KyelJmD

回答

0

我相信這應該只是工作:

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

也許問題出在病人的構造函數或什麼東西?

+0

不,不幸的是,代碼也不起作用。 – TheJaberwocky

+0

已修復! Seee OP(由於我的代表如此之低,無法在發佈後的8小時內回答我自己的問題)。 – TheJaberwocky

0

問題的代碼更改爲以下解決:

// 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(); 
相關問題