有個疑惑,next(),nextint(),這兩個是讀取回車或者空格之前的內容,回車和空格會滯留在快取區,后面跟nextline(),會導致直接接識訓車,結束接收,那nextline()接識訓車之前的內容,回車也在快取區,為什么后面跟netxline(),不影響???next(),nextint()方法查了資料,說是會自動將過濾掉有效字符前的回車或空格等無效字符
uj5u.com熱心網友回復:
檔案里寫的很清楚public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
netxline()會把換行符之前的資料回傳(不包括換行符),但也把指標移到了下一行,也就是雖然沒讀入換行符,但是會跳過它直接進入下一行的開頭
至于next(),nextint()會自動將過濾掉有效字符前的回車或空格等無效字符,看下面的例子
Scanner sc = new Scanner("abc\n\n\n 123 \n\n\n 456 789");
System.out.printf("[%s], [%d], [%s], [%s]\n", sc.nextLine(), sc.nextInt(), sc.nextLine(), sc.next());
next(),nextint()會過濾掉前面的無效字符,但是讀入資料后不會自動跳到下一個有效的字符(也就是后面的空白和回車依然滯留),而nextLine會跳過緊接其后的回車符
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/20925.html
標籤:Java SE
上一篇:求無限回圈小數位數?
