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();
}
}
}
|
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。