2014-04-25 40 views
0

我試圖在屏幕上打印一條消息,然後從鍵盤獲取一個值。我有4行打印,但我有他們之間的掃描方法。當我運行我的代碼時,前兩個打印一起運行,並且在第一次打印後,我無法在第一個變量中插入值。Java將兩行打印在一起

case 1: 
      System.out.println("###Book Data###"); 
      System.out.print("Name of the book:\t"); 
      String Name = key.nextLine(); 

      System.out.print("ISBN of the book:\t"); 
      String ISBN = key.nextLine(); 

      System.out.print("Author of the book:\t"); 
      String author = key.nextLine(); 

      System.out.print("Copies of the book:\t"); 
      int copies = key.nextInt(); 
      book Book = new book(ISBN,Name,author,copies); 
      lib.AddBook(Book); 
      break; 


#########Text Printed###### 
Please enter your selection: 1 
###Book Data### 
Name of the book:  ISBN of the book: 

在此先感謝您的幫助!

回答

2

println在打印不成的時候換行。你應該考慮或者使用的println,刷新緩衝區,或調用一個新行轉義字符「\ n」

1

這是因爲你上面的switch語句行有key.nextInt()*

掃描器讀取整數,但它將行尾字符'\n'留在緩衝區中。在switch語句中的key.nextLine();返回一些相關數據給您之前,您需要以某種方式使用'\n'字符。

要解決此問題,在switch語句的前面插入

key.nextLine(); 

*不要問我我怎麼知道:-)

+0

是的作品!你能解釋一下爲什麼會發生這種情況,或者要找出解決問題的方法? – Seekerakos

+0

@Seekerakos'掃描儀'保持鍵盤輸入緩衝區的「指針」。當用戶輸入東西時,字符進入緩衝區。從掃描儀讀取時,字符會從緩衝區中移除。您要求用戶輸入菜單選項;他按下'1',然後點擊[Enter]。您的代碼從掃描儀讀取'nextInt()',採用「1」。 '[Enter]'仍然存在。現在你要求'case'語句中的'nextLine()'。 'Scanner'看到'[Enter]',所以它立即返回給你一個空行! – dasblinkenlight

+0

如果我插入key.close();它會做同樣的事情,因爲我instert key.nextLine();在我切換之前? – Seekerakos