avatar

Java常用类_Scanner类

Scanner类


1 介绍

Scanner类功能: 读取键盘输入数据
Scanner类使用方法:

    1. 导包
1
import java.util.Scanner;
    1. 创建
1
Scanner sc = new Scanner(System.in); // System.in 作为Scanner的构造方法的参数是几乎不变的,代表着是从键盘输入的
    1. 使用 :
1
2
int num = sc.nextInt(); // 获取键盘输入的数字
String str = sc.next(); // 获取键盘输入的字符串

键盘输入的都是字符串,nextInt 只是将字符串转换成数字。当读取多个int型数据时,可以多次用nextInt 方法接数据,回车再输入或是空格输入均可

2 应用

2.1 hasNext() 和 next() 方法
1
2
3
if (scan.hasNext()) {
str = scan.next();
}

运行结果

1
2
3
4
5
IN : jieshu le
OUT: jieshu // 只输出 jieshu

IN : jieshu // 这里直接回车
OUT: jieshu

hasNext()方法当接收到字符时,会返回true;但收到空格或者回车时,返回false

2.2 nextLine() 和 hasnextLine() 方法
1
2
3
if (sc.hasNextLine()) {
str = sc.nextLine();
}

运行结果

1
2
IN : jieshu le  // 这里输入了回车
OUT: jieshu le

hasNextLine()方法当接收到空格时,返回false

3 next() 与 nextLine() 的总结

  • next(): next() 不能得到带有空格的字符串。
  • nextLine(): : nextLine()可以接收空白,以回车作为结束符。
  • 如果要输入intfloat 类型的数据,在 Scanner 类中也有支持,但是在输入之前最好先使用 hasNextxxx() 方法进行验证,再使用 nextxxx() 来读取。

4 小小的应用

今天恰巧遇到一个算法题,需要接收一些数据,输入方法:

1
2
3
4
5
6
5  // 总数
10 // 从这里开始total个数据
1
10
1
10

应用 Scanner 类可以这样写

1
2
3
4
5
6
7
8
9
10
int total =0 ;

Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
total = sc.nextInt();
}
int[] array = new int[total];
for(int i=0;i<total ;i++){
array[i] = sc.nextInt();
}
Author: TheOutsider
Link: http://yoursite.com/2020/03/29/Java%E5%B8%B8%E7%94%A8%E7%B1%BB_Scanner%E7%B1%BB/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.