16:Scanner类
Scanner类
Scanner是Java提供的一个工具类,我们可以通过Scanner类来获取用户的输入。即可以实现键盘输入数据到程序当中
基本语法:
Scanner s = new Scanner(System in);
- 通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入数据。
使用next方式,其实例如下:
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描对象,用于接受键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接受");
//判断用户是否输入字符串
if (scanner.hasNext()){
//使用next方式接受
String str = scanner.next();
System.out.println("输入的内容为" + str);
}
//凡是属于IO流的类如果不关闭会一直占用资源,需要养成用完就关闭的习惯
scanner.close();
}
}
运行结果如下
使用next方式接受
Hello word;
输入的内容为Hello
next()方式的注意事项:
- 一定要读取到有效字符后才可以结束输入。
- 对输入有效字符之前的空白,next()方法会自动将其去掉。
- 只有输入有效字符后才会将后面的输入空白作为分隔符或结束符。
- next()不能得到带有空格的字符串。
使用nextLine方式,其实例如下:
public class Demo02 {
public static void main(String[] args) {
//创建一个扫描对象,用于接受键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方式接受");
//判断用户是否输入字符串
if (scanner.hasNextLine()){
//使用nextLine方式接受
String str = scanner.nextLine();
System.out.println("输入的内容为" + str);
}
//凡是属于IO流的类如果不关闭会一直占用资源,需要养成用完就关闭的习惯
scanner.close();
}
}
运行结果如下:
使用nextLine方式接受
hello word !
输入的内容为hello word !
nextLine()方式的注意事项:
- nextLine()方法返回的是输入回车之前的所有字符。
- 可以获得空白。
如果要输入 int 或 float 类型的数据,在 Scanner 类中也有支持,但是在输入之前最好先使用 hasNextXxx() 方法进行验证,再使用 nextXxx() 来读取。
代码如下:
public class Demo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 从键盘接收数据
int i = 0;
float f = 0.0f;
System.out.print("输入整数:");
if (scanner.hasNextInt()) {
// 判断输入的是否是整数
i = scanner.nextInt();
// 接收整数
System.out.println("整数数据:" + i);
} else {
// 输入错误的信息
System.out.println("输入的不是整数!");
}
System.out.print("输入小数:");
if (scanner.hasNextFloat()) {
// 判断输入的是否是小数
f = scanner.nextFloat();
// 接收小数
System.out.println("小数数据:" + f);
} else {
// 输入错误的信息
System.out.println("输入的不是小数!");
}
scanner.close();
}
}
运行结果如下:
输入整数:3
整数数据:3
输入小数:2.3
小数数据:2.3
可以输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果。
代码如下:
public class Demo04 {
public static void main(String[] args) {
System.out.println("请输入数字:");
Scanner scanner = new Scanner(System.in);
double sum = 0;
int m = 0;
while (scanner.hasNextDouble()) {
double x = scanner.nextDouble();
m = m + 1;
sum = sum + x;
}
System.out.println(m + "个数的和为" + sum);
System.out.println(m + "个数的平均值是" + (sum / m));
scanner.close();
}
}
运行结果:
请输入数字:
34
43
234
end
10个数的和为585.0
10个数的平均值是58.5

浙公网安备 33010602011771号