java的快讀
(1)BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//定義對象String[] strings = br.readLine().split(" ");//讀取一行字符串,以空格為分隔轉化為字符串數組int n = Integer.parseInt(strings[0]);//讀取整數,字符串轉化為Integer類型數字long m = Long.parseLong(strings[1]); //讀取整數,字符串轉化為Long類型數字System.out.println(n + " "+m);strings = br.readLine().split(" ");System.out.println(strings[0]);//讀取字符串
(2)StreamTokenizer
該類的使用較為麻煩,可以封裝為一個對象,減低代碼量。他比BufferedReader快,但是對于讀取字符類型的操作,只能讀取26字母,特殊符號和數字無法讀取,有其局限性。
public class Main{static class Read{StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));public int nextInt() throws Exception{st.nextToken();return (int)st.nval;}public String readLine() throws Exception{ //有局限,慎用st.nextToken();return st.sval;}}
public static void main(String[] args) throws Exception {Read read = new Read();int n = read.nextInt();System.out.println(n);
}
}
StreamTokenizer常見錯誤
(1)StreamTokenizer讀入long類型的數字時會出現錯誤,因為nval的類型是double,在轉換為long類型的過程中,由于double的精度問題,當long類型讀入太大的數字時會出錯。double類型能表示的數字范圍比long大,但是是以犧牲精度的方式獲得更大的存儲,而他能精確保存的數字位數為十進制的15或16位,要比long小。
public class 快讀{static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));static StreamTokenizer sr = new StreamTokenizer(in);static long ans = 0;public static void main(String[] args) throws IOException {long n = nextLong();System.out.println(n);}static long nextLong() throws IOException {sr.nextToken();System.out.println(sr.nval);return (long) sr.nval;}
}
由圖可以看見,double類型在存儲時,犧牲了精度,導致結果不準確。
(2)StreamTokenizer讀入太長的字符串時也會有問題