Java Scanner 中的nextLine()鍵盤輸入異常情況解決

今天小黃遇到了:
Scanner f = new Scanner(System.in);
f.nextInt();
f.nextLine();
f.nextLine();
上面這三行語句只能執行上下兩句,中間一句的輸入不見了,
後來才發現中間的nextLine()讀取了nextInt()最後的Enter,導致它直接算輸入完畢,
我覺得這是個bug.
最後也是想出瞭解決辦法:
既然中間的nextLine()會讀前面的Enter,那麼我弄兩個Scanner對象它就讀不到了,嘿嘿嘿···
Scanner f = new Scanner(System.in);
Scanner w= new Scanner(System.in);
f.nextInt();
w.nextLine();
w.nextLine();
成功!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章