1.输入字符串
此类输入一般只包含单个字符串,如: abc123
Scanner sc = new Scanner(System.in);
String s = sc.nextLine(); // 读取一行字符串
2.输入数字
此类输入一般只包含单个数字,如:5
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); // 读取一个整数
3.输入字符串数组
此类输入一般会先在第一行输入长度n
,再在第二行输入长度为n
的数组。
数组可能会用空格隔开,如:
3
aaa bbb ccc
Scanner sc = new Scanner(System.in);
String[] lst = sc.nextLine().split(" "); // 用空格分割字符串
数组可能会用逗号隔开,如:
3
aaa,bbb,ccc
Scanner sc = new Scanner(System.in);
String[] lst = sc.nextLine().split(","); // 用逗号分割字符串
4.输入数字型数组
此类输入一般会先在第一行输入长度n
,再在第二行输入长度为n
的数组。
数组可能会用空格隔开,如
3
0 1 2
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
或者(可以处理数组长度n
未知的输入)
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer> nums = new ArrayList<>();
while (scanner.hasNextInt()) {
nums.add(scanner.nextInt());
}
数组可能会用逗号隔开,如:
3
0,1,2
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // Input array length
List<Integer> lst = new ArrayList<>();
scanner.nextLine(); // Move to the next line after reading the integer
String[] input = scanner.nextLine().split(",");
for (String num : input) {
lst.add(Integer.parseInt(num.trim()));
}
5.输入二维数组
此类输入一般会先在第一行输入二维数组的行数n
和列数吗m
,再在接下来的n
行输入长度为m
的字符串或者数组。
字符串类型 输入:
5 4
aaaa
bbbb
bbcc
ddee
ffgg
Scanner sc = new Scanner(System.in);
int height =sc.nextInt();
int width = sc.nextInt();
char map[][] =new char [height][width];
for(int i=0;i<heiht;i++){
map[i] =sc.nextLine().toCharArray();
}
5 4
0 0 0 0
0 0 0 1
1 1 1 2
2 2 2 3
3 3 4 4
Scanner sc = new Scanner(System.in);
int height = sc.nextInt();
int width = sc.nextInt();
int map[][] = new int [height][width];
for(int i=0;i < heiht;i++){
for(int j=0;i < width;j++){
map[i][j] = sc.nextInt();
}
}
6.输入树或图结构
这种输入一般会告诉你树/图结构的边数,然后输入节点编号之间的连接关系。一般而言,题目会告知输入每一条边时,哪个节点是父/子节点。如:
# 有向图一共有2条边
# 每条边输入时
# 第一个元素是父节点,第二个元素是子节点2
1 2
1 3# 一棵形如
# 1
# / \
# 2 3
# 的树形结构
一般采用构建邻接表的形式来表示一个图,而邻接表可以用哈希表很方便地表示。
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // Number of nodes
int m = scanner.nextInt(); // Number of edges
List<List<Integer>> g = new ArrayList<>(n + 1);
for (int i = 0; i <= n; i++) {
g.add(new ArrayList<>());
}
for (int i = 1; i <= m; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
// Directed graph
g.get(u).add(v);
7.输入次数若干,以某个标识符作为停止输入的标志
这种输入一般存在多组输入的情况,以某一标识符作为停止输入的标志。如输入若干行,以END
作为终止输入的标志:
0
1
2
END
这种输入一般需要结合while
循环进行。
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String str = scanner.next();
if (str.equals("END")) {
break;
}
// do something
}
8.输出
一般来说直接print()
即可。不可以在主函数中用return
代替print()
。
System.out.println(ans);
9.ACM模式与核心代码模式异同点总结