Java ACM 模式
输入
一维数据 Scanner
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
double d = sc.nextDouble();
}
}
二维数据 BufferedReader
注意导入包和抛出异常
import java.util.*;
import java.io.*;
public class Main {
static class Reader {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static String nextLine() throws IOException{// 读取下一行字符串
return reader.readLine();
}
static String next() throws IOException {// 读取下一个字符串
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {// 读取下一个int型数值
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {// 读取下一个double型数值
return Double.parseDouble(next());
}
}
}
使用例 1:readLine()
之后使用 split()
分割,不需要手搓工具类
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int n, m;
n = Integer.parseInt(input[0]);
m = Integer.parseInt(input[1]);
input = br.readLine().split(" ");
for (int i = 1; i <= n; i++) {
r[i] = Long.parseLong(input[i - 1]);
}
for (int i = 1; i <= m; i++) {
input = br.readLine().split(" ");
d[i] = Integer.parseInt(input[0]);
s[i] = Integer.parseInt(input[1]);
t[i] = Integer.parseInt(input[2]);
}
}
使用例 2:单独读取每个数据,需要手搓完整的工具类,用法和 Scanner
保持一致,需要避免 next()
和 nextLine()
混用
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throw Exception {
int n = Reader.nextInt();
double d = Reader.nextDouble();
// 如果需要long类型手动加即可
String s = Reader.next();
}
static class Reader {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static String nextLine() throws IOException{// 读取下一行字符串
return reader.readLine();
}
static String next() throws IOException {// 读取下一个字符串
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {// 读取下一个int型数值
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {// 读取下一个double型数值
return Double.parseDouble(next());
}
}
}
输出
一维数据 System.out
public static void main(String[] args) throws Exception {
System.out.println();
}
二维数据 BufferedWriter
-
write()
不带\n,注意传入数字时要转换为字符串 - 最后一定要使用
flush()
清空缓冲区,否则会有不输出的情况(都存在缓冲区里) close()
加不加随意
import java.util.*;
import java.io.*;
public class Main {
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception {
bw.write();
bw.write("\n");
// 清空缓冲区
bw.flush();
bw.close();
}
}