做算法或多或少会遇到超时,在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);
}
}
- 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(); //刷新缓存区