【发布时间】:2018-09-10 15:10:45
【问题描述】:
在使用 Java 的 nextInt() 方法时,我遇到了这段代码:
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
String string1 = scan.nextLine();
我知道 string1 将包含一个空字符串。我的问题是为什么像下面这样调用 nextLine 方法两次会给出错误:
String string1 = scan.nextLine().nextLine();
【问题讨论】:
-
因为
nextLine返回一个String而它没有nextLine成员函数。 -
Scanner#nextLine返回一个 字符串,而不是另一个Scanner对象。链接在这里没有什么意义。您想使用返回的字符串值。 -
(添加到现有的 cmets) 一般来说,您可能会看到这种现象称为“终端操作符”或“终端操作” - 这意味着方法返回的对象并不多或任何用于继续流或链的有用选项。在使用 Streams 时,这绝对是一个更常见的术语,但这个概念是全球性的。
-
感谢回归!
标签: java method-chaining