Java 扫描器前进线和returns 输入理解查询

Java scanner advances line and returns input understanding query

这更像是一个函数问题,我试图尽可能清楚地提出问题。

Java 手册指出:

nextLine(): Advances this scanner past the current line and returns the input that was skipped.

代码示例:

    // 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);

我正在尝试了解扫描仪功能正在推进哪些行以及正在跳过哪些行我知道发生了什么,但不知道为什么。

根据 JDK7 定义 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.

你看,当你调用nextLine()时,它会将指针(将其视为扫描仪开始扫描的点)移动到下一行,即跳过当前行。然后 nextLine() returns,无论它跳过什么。

因此,当您打电话时,

String userName = myObj.nextLine();

程序将跳过最后一行分隔符(这里是程序打印“Enter”后)用户输入的任何内容,并移至下一行。然后 nextLine() 方法 returns 以字符串形式跳过的数据。