java.util.Scanner類是一個簡單的文本掃描類,它能夠解析基本數據類型和字符串。它本質上是使用正則表達式去讀取不一樣的數據類型。java
java.io.BufferedReader類爲了可以高效的讀取字符序列,從字符輸入流和字符緩衝區讀取文本。正則表達式
用Scanner和BufferedReader兩種方式實現如下場景:
用命令行輸入一個數字m,若是m >1 輸出小於m的因此質數,包括m本身。緩存
Scanner 例子:命令行
package sjtejcys; import java.util.Scanner; public class Primes { public static void main(String[] args) { System.out.println("請輸入一個數字:"); Scanner sc = new Scanner(System.in); int m = sc.nextInt(); if(m>1){ if(m ==2) System.out.println(m); else { int j = 0; System.out.println(2); for(int i = 3;i<=m;i++){ for(j =2;j<m;j++) if(i%j == 0) break; if(j==i) System.out.println(i); } } } sc.close(); } }
BufferedReader 例子:code
package sjtejcys; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PrimesBF { public static void main(String[] args) { try { System.out.println("請輸入一個數字:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = null; while ((str = br.readLine()) != null) { int m = Integer.parseInt(str); if (m > 1) { if (m == 2) System.out.println(m); else { int j = 0; System.out.println(2); for (int i = 3; i <= m; i++) { for (j = 2; j < m; j++) if (i % j == 0) break; if (j == i) System.out.println(i); } } } } br.close(); } catch (IOException e) { e.printStackTrace(); } } }
簡單來講:
BufferedReader 是先把數據讀到緩存區而後在寫到硬盤裏
Scanner是直接往硬盤些數據
BufferedReader 的效率比Scanner高字符串