What's the difference between next() and nextLine() methods from Scanner class?

后端 未结 14 2439
你的背包
你的背包 2020-11-21 05:32

What is the main difference between next() and nextLine()?
My main goal is to read the all text using a Scanner which may be \"con

14条回答
  •  天命终不由人
    2020-11-21 06:19

    The key point is to find where the method will stop and where the cursor will be after calling the methods.

    All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.


    For example, consider the following illustration:

    |23_24_25_26_27\n
    

    | -> the current cursor position

    _ -> whitespace

    stream -> Bold (the information got by the calling method)

    See what happens when you call these methods:

    nextInt()    
    

    read 23|_24_25_26_27\n

    nextDouble()
    

    read 23_24|_25_26_27\n

    next()
    

    read 23_24_25|_26_27\n

    nextLine()
    

    read 23_24_25_26_27\n|


    After this, the method should be called depending on your requirement.

提交回复
热议问题