算法研习

一、输入输出

1.最常用的输入写法

1.1 读取一个整数

1
int n = sc.nextInt();

1.2 读取两个整数

1
2
3
4
int a = sc.nextInt();
int b = sc.nextInt();
//注:如果输入是1 2,那么得到的是a=1,b=2。
//nextInt()只会读取第一个整数,空格、换行都是分隔符,读完就停下。

1.3 读取一行字符串

1
2
String str = sc.next(); // 不带空格
String line = sc.nextLine(); // 读整行(带空格)

1.4 读取一组数字,存入数组(最常用!)

1
2
3
4
5
6
7
//输入例子:5 然后 1 2 3 4 5
int n = sc.nextInt(); // 先读长度
int[] arr = new int[n];

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

1.5 多组测试用例(循环输入)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//读多组输入,直到没有数据为止
while (sc.hasNextInt()) { // 只要还有整数输入就继续
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a + b);
}
//注:这里假设只有两个整数输入算和,hasNextInt()只判断下一个 token是不是整数,不是返还false
//除此以外也可以用sc.hasNext(),只要有内容就返回true,不管内容是数字、字母、符号。
//但最常用的是hasNextInt()。

//算法题目经常明确:第一行给数量,第二行给对应个数数据。
//所以读取方式是下面这样,先输入总个数 n,再输入 n 个数字。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// 后续随便处理数组
for(int num : arr){
System.out.print(num+" ");
}
}
}

2.最常用的输出写法

2.1 普通输出(换行)

1
System.out.println(结果);

2.2 不换行输出

1
System.out.print(结果);

2.3 格式化输出(保留小数等)

1
System.out.printf("%.2f", 3.14159); // 输出 3.14

3.输入输出模版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//基础模版
import java.util.Scanner; // 必须导入
public class Main {
public static void main(String[] args) {
// 1. 创建扫描器
Scanner sc = new Scanner(System.in);

// 2. 读数据
int a = sc.nextInt(); // 读整数
String s = sc.next(); // 读字符串
double d = sc.nextDouble(); // 读小数

// 3. 输出
System.out.println(a); // 输出并换行
System.out.print(s); // 输出不换行
}
}

//万能模版
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// 1. 读入数据
int n = sc.nextInt();

// 2. 处理逻辑(你写算法的地方)
int res = n * 2;

// 3. 输出结果
System.out.println(res);

sc.close();
}
}