Scanner,Random

Scanner类

Scanner类的功能:可以实现键盘输入数据到程序当中。

常用方法

int num = sc.nextInt():获取键盘输入的一个int数字

String str = sc.next():获取键盘输入的一个字符串

next():会自动消去有效字符前的空格和\n,只返回输入的字符。只有在读取到有效字符之后,才将其后的空格键、Tab键或Enter等消除。

nextLine():方法返回的是Enter键(\n)之前的所有字符,它是可以得到带空格的字符串的,当读取到\n时,自动进行换行

hasNext():会判断接下来是否有非空字符(不包括空行,\n)。如果有,则返回true,否则返回false

hasNextLine():会根据行匹配模式去判断接下来是否有一行(包括空行,换行符\n),如果有,则返回true,否则返回false,如果只有\n,也会返回true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Scanner; // 1. 导包
public class Demo01Scanner {
public static void main(String[] args) {
//2. 创建
// 备注:System.in代表从键盘进行输入
Scanner sc = new Scanner(System.in);

//3. 获取键盘输入的int数字
int num = sc.nextInt();
System.out.println("输入的int数字是:" + num);

//4. 获取键盘输入的字符串
String str = sc.next();
System.out.println("输入的字符串是:" + str);
}
}

ACM常用输入模板

1
2
3
4
5
6
7
8
9
10
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while (in.hasNext()){
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a+b);
}
}
}

Random类

Random类用来生成随机数字

int num = r.nextInt():获取一个随机的int数字(范围是int所有范围,有正负两种)

int num = r.nextInt(3):获取一个随机的int数字(参数代表了范围,左闭右开区间),实际上代表的含义是:[0,3),也就是0~2

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
int n = 5;
Random r = new Random();
for (int i = 0; i < 100; i++) {
// 本来范围是[0,n),整体+1之后变成了[1,n+1),也就是[1,n]
int result = r.nextInt(n) + 1;
System.out.println(result);
}
}

Scanner,Random
http://example.com/2023/05/13/Java/Java常用类/Scanner、Random/
作者
PALE13
发布于
2023年5月13日
许可协议