【问题标题】:Java scanner advances line and returns input understanding queryJava扫描器前进行并返回输入理解查询
【发布时间】:2020-07-25 03:22:46
【问题描述】:

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

Java 手册指出:

nextLine()前进此扫描仪越过当前行并返回被跳过的输入。

代码示例:

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

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

【问题讨论】:

  • 具体来说,它从输入流中读取,直到遇到下一个换行符/换行符(IIRC 取决于平台;在 Windows 上,它将是序列 \r\n,但在 linux 上它将是 \n。对于大多数实际目的而言,它应该无关紧要),一旦它刚刚通过所述换行符就停止并返回它在到达那里的过程中传递的所有内容。

标签: java class scanning


【解决方案1】:

根据 JDK7 定义 nextLine()

将此扫描器前进到当前行并返回被跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。

看,当您调用nextLine() 时,它会将指针(将其视为扫描仪开始扫描的点)移动到下一行,即跳过当前行。然后nextLine() 返回,不管它跳过了什么。

因此,当你打电话时,

String userName = myObj.nextLine();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多