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 intlen;

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

numsi = sc.nextInt();

}

// 8. 读一个 long\[\]

int len2 = sc.nextInt();

long\[\] arrLong = new longlen2;

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

arrLongi = sc.nextLong();

}

// 9. 读一个 String\[\]

int len3 = sc.nextInt();

String\[\] strs = new Stringlen3;

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

strsi = sc.next();

}

// 10. 读一个 char\[\]

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

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

int rows = sc.nextInt();

int cols = sc.nextInt();

int\[\]\[\] grid = new introwscols;

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

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

gridij = sc.nextInt();

}

}

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

int m = sc.nextInt();

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

String\[\]\[\] lines = new Stringm\[\];

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

linesi = 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 intn;

for (int i = 0; i < n; i++) numsi = 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 intn;

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

numsi = sc.nextInt();

}

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

String line = sc.nextLine();

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

}

}

相关推荐
笑小枫6 分钟前
用 Claude Code 推翻重写笑小枫网站
java·人工智能·spring boot·ai编程
霸道流氓气质19 分钟前
ApiPost 中配置自动获取 Token 并调用业务接口完整指南
java·服务器·数据库
独隅40 分钟前
IntelliJ IDEA 接入多种AI大模型插件终极指南(2026.1 企业合规版)
java·人工智能·intellij-idea
还是奇怪1 小时前
Simon Willison 用 DSPy 优化 Datasette Agent 提示词:提示工程正在变成可测试的软件工程
java·开发语言·软件工程
zfoo-framework1 小时前
1.ansible安装 2.虚拟机克隆
java
码上解惑2 小时前
从 Dify 工作流说起:常用节点怎么选、怎样组合?
java·人工智能·ai·agent·dify·智能体·spring ai
稚南城才子,乌衣巷风流2 小时前
ST 表(Sparse Table)算法详解:原理、实现与应用
算法
hold?fish:palm2 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle2 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木2 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先