Java Scanner 的 ACM 常用输入模板

• 下面给你一版 Java Scanner 的 ACM 常用输入模板,够笔试直接套。

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// 1. 读一个 int

int n = sc.nextInt();

// 2. 读一个 long

long x = sc.nextLong();

// 3. 读一个 double

double d = sc.nextDouble();

// 4. 读一个 String(不含空格)

String s1 = sc.next();

// 5. 读一整行 String(可包含空格)

sc.nextLine(); // 如果前面用了 nextInt/next/nextLong 等,要先清理回车

String s2 = sc.nextLine();

// 6. 读一个 char

char c = sc.next().charAt(0);

// 7. 读一个 int[]

int len = sc.nextInt();

int[] nums = new int[len];

for (int i = 0; i < len; i++) {

nums[i] = sc.nextInt();

}

// 8. 读一个 long[]

int len2 = sc.nextInt();

long[] arrLong = new long[len2];

for (int i = 0; i < len2; i++) {

arrLong[i] = sc.nextLong();

}

// 9. 读一个 String[]

int len3 = sc.nextInt();

String[] strs = new String[len3];

for (int i = 0; i < len3; i++) {

strs[i] = sc.next();

}

// 10. 读一个 char[]

char[] chars = sc.next().toCharArray();

// 11. 读一个二维 int 数组

int rows = sc.nextInt();

int cols = sc.nextInt();

int[][] grid = new int[rows][cols];

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

grid[i][j] = sc.nextInt();

}

}

// 12. 读多行字符串数组(每行按空格分割)

int m = sc.nextInt();

sc.nextLine(); // 清理回车

String[][] lines = new String[m][];

for (int i = 0; i < m; i++) {

lines[i] = sc.nextLine().split(" ");

}

}

}

你最该记住的是这几条:

  1. 基本类型

int n = sc.nextInt();

long x = sc.nextLong();

double d = sc.nextDouble();

  1. 字符串

String s = sc.next(); // 读一个单词

String line = sc.nextLine(); // 读一整行

  1. 字符

char c = sc.next().charAt(0);

  1. 数组

int[] nums = new int[n];

for (int i = 0; i < n; i++) nums[i] = sc.nextInt();

  1. 字符数组

char[] chars = sc.next().toCharArray();

  1. 最重要的坑

如果前面用了:

nextInt() / nextLong() / next() / nextDouble()

后面想用:

nextLine()

通常都要先补一句:

sc.nextLine();

因为要清掉残留回车。


给你一版笔试最常用精简模板:

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int[] nums = new int[n];

for (int i = 0; i < n; i++) {

nums[i] = sc.nextInt();

}

sc.nextLine(); // 如果后面要读整行字符串

String line = sc.nextLine();

char[] chars = sc.next().toCharArray();

}

}

相关推荐
王老师青少年编程14 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮15 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说15 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
许彰午15 小时前
CacheSQL(二):主从复制——OpLog 环形缓冲区与故障自动恢复
java·数据库·缓存
wuweijianlove15 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
leoufung16 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了16 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
HXDGCL16 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
Bat U16 小时前
JavaEE|多线程初阶(七)
java·开发语言
谭欣辰16 小时前
C++ 排列组合完整指南
开发语言·c++·算法