英文:
Java scanner advances line and returns input understanding query
问题
这更多是一个关于函数的问题,我尽量以清晰的方式提问。
Java手册中说明:
> nextLine()
: 使扫描器前进到下一行,并返回被跳过的输入。
示例代码:
// 创建新的扫描器类 myObj,从用户获取 System.in。
Scanner myObj = new Scanner(System.in);
// 打印提示给用户。
System.out.println("输入");
// 将 myObj 从 System.in 输入分配到 userName 字符串中。
String userName = myObj.nextLine();
// 打印 userName、myObj 或 System.in 输入的输出。
System.out.print(userName);
我试图理解哪些行是被扫描器函数跳过的,以及被跳过的是什么。我理解发生了什么,但不明白为什么。
英文:
This is more of a function question which I am attempting to ask as clear as possible.
Java handbook states:
> nextLine()
: Advances this scanner past the current line and returns the input that was skipped.
Code for example:
// Create new scanner class myObj, receive System.in from user.
Scanner myObj = new Scanner(System.in);
//Print prompt for user.
System.out.println("Enter");
//Allocate myObj input from System.in into userName string.
String userName = myObj.nextLine();
//Print output of userName, myObj or System.in input.
System.out.print (userName);
I am trying to understand which lines are being advanced over with the scanner function and what is being skipped I understand what is occurring but not why.
答案1
得分: 2
nextLine()
方法的定义根据JDK7的说明如下:
使此扫描器前进到当前行的末尾并返回被跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置将被设置为下一行的开头。
当你调用nextLine()
时,它会将指针(可以将其视为扫描器开始扫描的位置)移到下一行,也就是跳过了当前行。然后,nextLine()
方法会返回它所跳过的内容。
因此,当你调用:
String userName = myObj.nextLine();
程序会跳过用户在最后一行分隔符(在这里是程序打印出的“Enter”后面)之后输入的任何内容,并移到下一行。然后,nextLine()
方法将以字符串形式返回被跳过的数据。
英文:
Definition of nextLine()
as per JDK7.
> 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.
Look, when you call nextLine()
, it moves the pointer(think of it as the point from where the scanner start scanning), to the next line, that is, it skips the current line. Then the nextLine()
returns, whatever it has skipped.
Therefore, when you call,
String userName = myObj.nextLine();
The program skips whatever the user has entered after the last line separation (here, after the program prints, "Enter") and moves to the next line. Then the nextLine()
method returns the skipped data in the form of a string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论