Java快读

java的快读

(1)BufferedReader

java 复制代码
    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字母,特殊符号和数字无法读取,有其局限性。

java 复制代码
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小。

java 复制代码
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读入太长的字符串时也会有问题

相关推荐
Blossom.11810 小时前
AI编译器实战:从零手写算子融合与自动调度系统
人工智能·python·深度学习·机器学习·flask·transformer·tornado
柯慕灵10 小时前
7大推荐系统/算法框架对比
算法·推荐算法
adam-liu10 小时前
Fun Audio Chat 论文+项目调研
算法·语音端到端·fun-audio-chat
Coder_Boy_10 小时前
SpringAI与LangChain4j的智能应用-(理论篇3)
java·人工智能·spring boot·langchain
栀秋66611 小时前
你会先找行还是直接拍平?两种二分策略你Pick哪个?
前端·javascript·算法
Coder_Boy_11 小时前
基于SpringAI的智能平台基座开发-(六)
java·数据库·人工智能·spring·langchain·langchain4j
如果你想拥有什么先让自己配得上拥有11 小时前
数学思想和数学思维分别都有什么?
线性代数·算法·机器学习
热爱专研AI的学妹11 小时前
数眼搜索API与博查技术特性深度对比:实时性与数据完整性的核心差异
大数据·开发语言·数据库·人工智能·python
Mr_Chenph11 小时前
Miniconda3在Windows11上和本地Python共生
开发语言·python·miniconda3
长安er11 小时前
LeetCode136/169/75/31/287 算法技巧题核心笔记
数据结构·算法·leetcode·链表·双指针