JDK1.8源码-13-Scanner

JDK1.8使用-13-Scanner

前序

在笔试编程过程中,关于数据的读取如果迷迷糊糊,那后来的编程即使想法很对,实现很好,也是徒劳,于是在这里认真总结了Java Scanner 类的使用

常用方法:next()和nextline()

mark

  • 上图的方法:只读取对应数据类型的数据,如果输入了非对应数据类型的数据就是报错。
  • 比如:nextlnt():只读取int值,就是只能读取整数类型的数据,如果输入了非整型的数据(浮点型字符串等)就会报错。
    nextFloat()、nextDouble()这些也是以此类推,只能读取符合该类型的数据。
  • next() : 只读取输入直到空格,它不能读取两个由空格或者符号隔开的单词。此外next() 在读取输入后将光标放入到同一行中
  • nextLine():读取输入,包括单词之间的空格和除回车意外的所有符号(即它会读到行尾)。读取输入后,nextLine()会将光标定位在下一行。

废话不多说:show me the code

  • 源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public int nextInt() {
return nextInt(defaultRadix);
}

/**
* Scans the next token of the input as an <tt>int</tt>.
* This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid int value as
* described below. If the translation is successful, the scanner advances
* past the input that matched.
*
* <p> If the next token matches the <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into an <tt>int</tt> value as if by
* removing all locale specific prefixes, group separators, and locale
* specific suffixes, then mapping non-ASCII digits into ASCII
* digits via {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Integer#parseInt(String, int) Integer.parseInt} with the
* specified radix.
*
* @param radix the radix used to interpret the token as an int value
* @return the <tt>int</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
  • 测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个字符串(中间能加空格或符号)");
String a = input.nextLine();
System.out.println("请输入一个字符串(中间不能加空格或符号)");
String b = input.next();
System.out.println("请输入一个整数");
int c = input.nextInt(); // 只能读取Int
System.out.println("请输入一个double类型的小数");
double d= input.nextFloat();
System.out.println("请输入一个float类型的小数");
float f = input.nextFloat();



System.out.println("按顺序输出abcdf的值:");
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(f);
}
  • 运行输入:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
请输入一个字符串(中间能加空格或符号)
我爱祖国!
请输入一个字符串(中间不能加空格或符号)
ILoveChina
请输入一个整数
520
请输入一个double类型的小数
12.26e3
请输入一个float类型的小数
3.1415926
按顺序输出abcdf的值:
我爱祖国!
ILoveChina
520
12260.0
3.1415925

常用用法:hasNext()

mark

  • 源码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public boolean hasNextInt() {
return hasNextInt(defaultRadix);
}

/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the specified radix using the
* {@link #nextInt} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as an int value
* @return true if and only if this scanner's next token is a valid
* int value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextInt(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
// 返回一个boolean的值
return result;
}
  • 测试用例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static void main(String[] args) {
// 通过Scanner构造函数接收控制台输入的信息
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的姓名");
// 接收一个字符串,可以加出回车键意外所有的信息,包括空格和Tab
String name = scanner.nextLine();
System.out.println("请输入你的ID");
String ID;

// 循环判断hasNextLine()方法是否有输入(返回true或false)
while (scanner.hasNextLine()){
// 如果输入的是整型类型,当为整型类型执行循环
if (scanner.hasNextInt()){
ID = scanner.nextLine();
System.out.println("你输入的姓名为:"+name);
System.out.println("你输入的ID为:"+ID);
break;
}else {
System.out.println("请输入数字哦!");
ID = scanner.nextLine();
continue;
}
}
}
  • 运行测试
1
2
3
4
5
6
7
8
请输入你的姓名
朱酱酱
请输入你的ID
qq353446503
请输入数字哦!
353446503
你输入的姓名为:朱酱酱
你输入的ID为:353446503

Demo:键盘输入求平均数

  • 注意:如果要输入int 或者 float … 之类的数据,在Scanner中输入之前最好先使用hasNextXxx() 方法进行验证,再使用nextXxx()进行读取接收
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

double sum = 0;
int m = 0;


while (scanner.hasNextDouble()){
// 接收dobule的值
double x = scanner.nextDouble();
m = m + 1;
sum = sum + x;
}


System.out.println(m + "个数的和为" + sum);
System.out.println(m + "个数的平均值是" + (sum / m));
scanner.close();
}
  • 测试用例:
1
2
3
4
5
6
7
请输入数字:
20.0
30.0
40.0
end
3个数的和为90.0
3个数的平均值是30.0s
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信