1. 程式人生 > >Java中Scanner的理解大總結

Java中Scanner的理解大總結

Scanner類常用的方法:

Scnaner(File file);Scnaner(String filename);建立一個從特定檔案掃描的掃描器
hasNext();還有可讀取的書庫返回true
next();返回下一個標誌作為字串
nextLine();使用行分隔符從這個掃描器返回一個行結束
nextByte();nextshort();nextInt();nextLong();nextFloat();nextDouble();分別返回一個對應型別的值
useDelimiter(string pattern);設定這個掃描器的分割模式並返回這個掃描器

一,從控制檯輸入


當通過new Scanner(System.in)建立一個Scanner,控制檯會一直等待輸入,直到敲回車鍵結束,把所輸入的內容傳給Scanner,作為掃描物件。如果要獲取輸入的內容,則只需要呼叫Scanner的nextLine()方法即可

public class scanner { 
        public static void main(String[] args) { 
                Scanner s = new Scanner(System.in); //從控制檯輸入
                System.out.println("請輸入字串:"
); while (true) { String line = s.nextLine(); System.out.println( line); } } }

Scanner預設使用空格作為分割符來分隔文字

public static void main(String[] args) throws FileNotFoundException { 
  Scanner s = new
Scanner("123 456 789"); while (s.hasNext()) { System.out.println(s.next()); } } //輸入結果就是 123 456 789

二,從檔案掃描讀入
Scanner的構造器支援多種方式,構建Scanner的物件很方便,可以從字串(Readable)、輸入流、檔案等等來直接構建Scanner物件,有了Scanner了,就可以逐段(根據正則分隔式)來掃描整個文字,並對掃描後的結果做想要的處理。

Scanner(File file) //構造一個新的Scanner,它生成的值是從指定檔案掃描的
Scanner(InputStream source) //構造一個新的 Scanner,它生成的值是從指定的檔案的輸入流掃描的
Scanner(String filename) //構造一個新的Scanner,它生成的值是從指定檔名掃描的。
檔案物件,檔名,檔案輸入流

public static void main(String[] args) throws FileNotFoundException { 
 InputStream in = new FileInputStream(new File("score.txt")); 
     Scanner s = new Scanner(in);//檔案輸入流
   //new Scanner("score.txt");new Scanner(new file("score.txt"));都可以
                while(s.hasNextLine()){ 
                        System.out.println(s.nextLine()); 
                } 
        }

三,Scanner是怎麼工作的
next();nextByte();nextshort();nextInt();nextLong();nextFloat();nextDouble();都是令牌讀取方法,他們分隔符預設情況下是空格。

next()和nextLine() 的區別:

next()方法讀取一個由分割付分割的字元,但是nextLine()是讀取一個以行分割符結束的行
例如test.txt文字中有
23 345

Scanner input=new Scanner(new File("test.txt"));
int a=input.next();
String line=input.nextLine();//要讀到行分隔符

的結果是a的值是34 ,line的值是”,”3,’4’,’5’
再如如果從鍵盤輸入23,然後按回車鍵,接著輸入345,然後在按鈕回車鍵,執行

Scanner input=new Scanner(new File("test.txt"));
int a=input.next();
String line=input.nextLine();//要讀到行分隔符

之後的結果是a的值是23,但是line的卻是空的字串,因為nextInt()讀取到23,然後在分割付處停止,這裡的分隔符是行分隔符,就是回車鍵,所以nextLine還沒有到資料就結束了,為空字串。