Java中有一个类Scanner用于读取用户在命令行输入的信息。
Scanner类需要导入包java.util.Scanner
1
2
3
4
5
6
7
8
9
10
11
12
13
|
nextLine()
方法读取用户输入字符。Scanner还有其它方法。
nextBigDecimal() nextByte() nextShort() nextInt() nextLong() nextFloat() nextDouble() nextBoolean()
这些方法用于读取不同类型的数据。
有了Scanner类我们能做些人机交互程序,如猜数游戏:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import
java.util.Scanner;
public
class
MyClass {
public
static
void
main(String[] args) {
// 创建一个scanner对象
int
randomNumber = (
int
)(Math.random()*
10
);
// 读取用户输入的数
int
value = scanner.nextInt();
while
(value!=randomNumber){
randomNumber = (
int
)(Math.random()*
10
);
value = scanner.nextInt();
}
}
}
|