《Java核心技术》学习之路(二)

来源:互联网 发布:mysql数据库文件太大 编辑:程序博客网 时间:2024/05/16 14:09

在《Java核心技术(第9版)》P54——3.7一节中有两个Scanner方法next和nextLine,这两个方法有什么区别呢?

根据官方API文档

public String next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息。即使以前调用 hasNext() 返回了 true,在等待要扫描的输入时此方法也可能阻塞。

public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

此扫描器执行当前行,并返回跳过的输入信息。 此方法返回当前行的其余部分,不包括结尾处的行分隔符。当前位置移至下一行的行首。 
因为此方法会继续在输入信息中查找行分隔符,所以如果没有行分隔符,它可能会缓冲所有输入信息,并查找要跳过的行。

public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.

将输入信息的下一个标记扫描为一个 int。 
此方法调用 nextInt() 的行为与调用 nextInt(radix) 完全相同,其中的 radix 是此扫描器的默认基数。 


简单点说就是next()读取输入的下一个单词(以空格作为分隔符),nextLine()读取输入的下一行内容,而nextInt()获取数值。


下面说说我遇到的问题,根据书中编写代码:

import java.util.*;public class Welcome {public static void main(String[] args){Scanner in = new Scanner(System.in);System.out.println("What's your name?");String name = in.next();System.out.println("How old are you?");int age = in.nextInt();System.out.println("Hello, " + name + ", Next year, you'll be " + (age + 1));}}
当我输入

===========================================

What's your name?
a
How old are you?
1
Hello, a, Next year, you'll be 2

==========================================
但是当我输入

===========================================

What's your name?
a b
How old are you?
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Welcome.main(Welcome.java:10)

=============================================

为什么会提示这样的错误呢?

根据错误信息,我们可以知道,系统提示获取的标记与期望类型的模式不匹配,或者该标记超出期望类型的范围。

照理说,我输入a b,next()只会获取字符a,然后执行下一条语句,此时不匹配是指的什么呢?难道是b与nextInt()不匹配吗?

那么我尝试着修改输入为

=================================================

What's your name?
a 1
How old are you?
Hello, a, Next year, you'll be 2

=================================================

此时一切正常,说明,应该是b与nextInt()不匹配导致的,那么为什么会出现这种情况呢?

我们再来看next()的处理机制便清楚了

0 0
原创粉丝点击