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

相关推荐
软件技术NINI15 小时前
MATLAB疑难诊疗:从调试到优化的全攻略
javascript·css·python·html
一线大码15 小时前
SpringBoot 优雅实现接口的多实现类方式
java·spring boot·后端
花伤情犹在15 小时前
Java Stream 高级应用:优雅地扁平化(FlatMap)递归树形结构数据
java·stream·function·flatmap
yaoxin52112315 小时前
212. Java 函数式编程风格 - Java 编程风格转换:命令式 vs 函数式(以循环为例)
java·开发语言
Q_Q196328847515 小时前
python+uniapp基于微信小程序的助眠小程序
spring boot·python·小程序·django·flask·uni-app·node.js
ZYMFZ15 小时前
python面向对象
前端·数据库·python
wangqiaowq15 小时前
ImmutableList.of() 是 Google Guava 库 提供的一个静态工厂方法,用于创建一个不可变的(immutable)列表。
开发语言·windows·python
再卷也是菜15 小时前
C++篇(14)二叉树进阶算法题
c++·算法
摇滚侠15 小时前
Spring Boot 3零基础教程,WEB 开发 Thymeleaf 属性优先级 行内写法 变量选择 笔记42
java·spring boot·笔记