我試圖在屏幕上打印一條消息,然後從鍵盤獲取一個值。我有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:
在此先感謝您的幫助!
是的作品!你能解釋一下爲什麼會發生這種情況,或者要找出解決問題的方法? – Seekerakos
@Seekerakos'掃描儀'保持鍵盤輸入緩衝區的「指針」。當用戶輸入東西時,字符進入緩衝區。從掃描儀讀取時,字符會從緩衝區中移除。您要求用戶輸入菜單選項;他按下'1',然後點擊[Enter]。您的代碼從掃描儀讀取'nextInt()',採用「1」。 '[Enter]'仍然存在。現在你要求'case'語句中的'nextLine()'。 'Scanner'看到'[Enter]',所以它立即返回給你一個空行! – dasblinkenlight
如果我插入key.close();它會做同樣的事情,因爲我instert key.nextLine();在我切換之前? – Seekerakos