Scanner中next()與nextLine()的區(qū)別
在給出的第一章作業(yè)參考的代碼中,將String?name?=?console.next();換成String?name?=?console.nextLine(); 導(dǎo)致代碼運(yùn)行在選擇名稱輸出1之后,會(huì)直接拋出異常,是因?yàn)槭裁矗?private?static?String?getBookByName(String[]?books) throws?Exception?{ System.out.println("輸入圖書名稱:"); //獲取輸入的圖書名稱 String?name?=?console.next(); for?(int?i?=?0;?i?<?books.length;?i++)?{ if?(name.equals(books[i])) //輸入的名稱與某一圖書名稱匹配,返回該圖書 return?books[i]; } //若無(wú)匹配,拋出”圖書不存在異?!? throw?new?Exception("圖書不存在!"); }
2016-05-07
next()以讀取到有效字符(非空格,tab,enter)開始,中途遇到無(wú)效字符結(jié)束輸入,得不到帶無(wú)效字符的字符串,nextline()可以得到非enter的字符串