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

}

}

相关推荐
祖力555 小时前
数据结构的基本概念与单向链表(链表数据类型构造、创建、头插、尾插、头删、尾删)
数据结构·链表
大明者省6 小时前
WSL2 Ubuntu22.04 GPU训练环境配置指南
人工智能·算法·计算机视觉
嘻哈∠※7 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
白狐_7988 小时前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
zander2588 小时前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界
java·数据结构·算法
码匠许师傅8 小时前
【C++ 面试真题】聊聊 C++ 的拷贝构造与拷贝赋值
java·c++·面试
Shell运维手记8 小时前
Linux 常用基础命令学习笔记
linux·运维·笔记·学习·算法·github
杨航 AI8 小时前
O(n log n):线性对数原理拆解 这个是排序算法的黄金复杂度之一。
算法·排序算法
船厂电气自动化ai大模型9 小时前
AI大模型与数学 第32课 函数凹凸性与二阶导数:拐点求解、凹凸区间计算(10道二阶导数计算题)
数据结构·人工智能·python·深度学习·算法
旖旎夜光9 小时前
LeetCode 3:无重复字符的最长子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口