Java中Scanner類用法總結

Scanner類簡介

Java 5添加了java.util.Scanner類,這是一個用於掃描輸入文本的新的實用程序。它是以前的StringTokenizer和Matchaer類之間的某種結合。由於任何數據都必須通過同一模式的捕獲組檢索或通過使用一個索引來檢索文本的各個部分。於是可以結合使用正則表達式和從輸入流中檢索特定類型數據項的方法。這樣,除了能使用正則表達式外,Scanner類還可以任意地對字符串和基本類型的數據進行分析。藉助於Scanner,可以針對任何要處理的文本內容編寫自定義的語法分析器。

關於nextInt(),next(),nextLine()的理解

nextInt():it only reads the int value,nextInt() places the cursor(光標)in the same line after reading the input.(nextInt()只讀取數字,剩下’\n’還沒有讀取,將crusor放在本行中)
next():read the input only till the space.It can’t read the two words separated by space.Also , next() places teh cursor in the same line after reading the input.(next()只讀空格之前的數據,並且cursor指向本行)
nextLine():reads input including space between the words (that is , it reads till the end of line\n).Once the input is read,nextLine() positions the cursor in the nextLine().
nextLine()時,則可以掃描到一行內容並作爲一個字符串而被獲取到。

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