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

}

}

相关推荐
辰烨chenye2 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
lhldsg5 小时前
全民健身解决方案小程序开发:从0到1的技术实战
java·数据库·需求分析
jason成都5 小时前
Spring WebFlux 适配达梦新方案|dm‑r2dbc:Netty 异步传输的实验性 R2DBC 驱动
java·后端·spring
泡海椒5 小时前
内置SPI函数库详解:JQuick-Java Builtin工具类实战用法
java·开发语言·python
hqyjzsb6 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
辰烨chenye6 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
微功夫信息技术6 小时前
分层多智能体强化学习驱动的非急救转运公平 - 效率统一调度系统研究与实践
人工智能·学习·算法·动态规划
小羊没烦恼!6 小时前
Hello Web API系列教程——Web API与国际化
java·服务器·前端·javascript·php
sanjiaomao3336 小时前
从论文公式到Python实现:用单元测试校验滑动平均算法
python·算法·单元测试
乐迪信息7 小时前
如何通过AI防爆摄像机精准判断船舶超速?
大数据·人工智能·算法·安全·目标跟踪