Java快速输入,输出

做算法或多或少会遇到超时,在java中应该是很常见的,下面介绍几种快速输入输出方法
快速输入
1 BufferedReader

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // 输入
		// 输入的一行字符
		String line = in.readLine(); 
		System.out.println(line);
	}
}

  1. StringTokenizer(个人推荐) 封装好的一个类,直接作为内部类使用
    /** 快速输入类 */
    static class Reader {
        static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        static StringTokenizer tokenizer = new StringTokenizer("");
        /** 获取下一段文本 */
        static String next() throws IOException {
            while ( ! tokenizer.hasMoreTokens() ) {
                tokenizer = new StringTokenizer(reader.readLine());
            }
            return tokenizer.nextToken();
        }
        static int nextInt() throws IOException {
            return Integer.parseInt( next() );
        }
        static double nextDouble() throws IOException {
            return Double.parseDouble( next() );
        }
    }

3.StreamTokenizer
这个限制就比较多,只能严格接收字母或者数字,其他特殊字符接收都是null
但是有一点很疑惑,StreamTokenizer 似乎比BufferedReader 更快一点
PAT上的题BufferedReader 过不了,但是 StreamTokenizer 能过
看大家取舍

static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    static StreamTokenizer in = new StreamTokenizer(reader);
    
    public static void main(String[] args) throws IOException {
		int n = nextInt();
		String a = next();
    }
    static String next() throws IOException {
        in.nextToken();
        return in.sval;
    }
    /** 获取数字 */
    static int nextInt() throws IOException {
        in.nextToken();
        return (int)in.nval;
    }
    static double nextDouble() throws IOException {
        in.nextToken();
        return in.nval;
    }

快速输出
PrintWriter

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
out.print(text);
out.flush(); //刷新缓存区
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海边的宇航员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值