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();

}

}

相关推荐
_upupup12 分钟前
异常(C++)
java·开发语言·jvm
g105655913916 分钟前
公有云_云运维服务
java·运维·服务器
hetao173383718 分钟前
2026-09-29 hetao1733837 的刷题记录
c++·算法
霸道流氓气质27 分钟前
ComfyUI 图像生成工作流完全指南:从节点编排到Java生产级图像生产实战
java·开发语言·人工智能
再写一行代码就下班38 分钟前
linux sh脚本在windows修改导致无法使用解决方式
java·linux·centos
欣欣之王来了1 小时前
AI合规专项:AI算法透明度的合规要求
人工智能·算法
wzdark1 小时前
分块思想在算法优化中的实践与应用4
算法
Because_of_Her11 小时前
dfs-洪水填充技巧
笔记·算法·深度优先·洪水填充
小静AI工程实验室1 小时前
RSA 算法详解:从模幂原理到 OAEP 加密、PSS 签名与 Python 实验
python·算法
m0_587383001 小时前
24小时自助健身房软硬件解决方案实战指南:从架构设计到部署实施
java·spring·小程序·架构·需求分析