Understanding Scanner's nextLine(), next(), and nextInt() methods

前端 未结 3 1185
独厮守ぢ
独厮守ぢ 2020-11-29 06:07

I am trying to understand how these three methods work. Here\'s how I understood them:

  • nextLine() reads the remainder of the current line even if
相关标签:
3条回答
  • 2020-11-29 06:44

    If your input is 2 hello hi

    nextInt() - just read the next token as a int (Here - it is 2) otherwise it give error

    next() - Just read the next token, (here - it is hello)

    nextline() - It read a line until it gets newline (here - after read previous 2 hello input by nextInt, next; nextline read hi only because after that it finds a newline )

    if input is

    2 
    
    Hi 
    
    Hello 
    

    nextInt, next is same for above discussion .

    In nextline(), it finds newline after completing the input Hi read by next(). So, nextline() stops to read input for getting the newline character.

    0 讨论(0)
  • 2020-11-29 06:45

    nextLine() reads the remainder of the current line even if it is empty.

    Correct.

    nextInt() reads an integer but does not read the escape sequence "\n".

    Correct1.

    next() reads the current line but does not read the "\n".

    Incorrect. In fact, the next() method reads the next complete token. That may or may not be the rest of the current line. And it may, or may not consume an end-of line, depending on where the end-of-line is. The precise behavior is described by the javadoc, and you probably need to read it carefully for yourself in order that you can fully understand the nuances.

    So, in your example:

    1. The nextInt() call consumes the 2 character and leaves the position at the NL.

    2. The next() call skips the NL, consumes H and i, and leaves the cursor at the second NL.

    3. The nextLine() call consumes the rest of the 2nd line; i.e. the NL.


    1 ... except that your terminology is wrong. When the data is being read, it is not an escape sequence. It is an end-of-line sequence that could consist of a CR, a NL or a CR NL depending on the platform. The escape sequences you are talking about are in Java source code, in string and character literals. They may >>represent<< a CR or NL or ... other characters.

    0 讨论(0)
  • 2020-11-29 06:45

    Does this mean that the method next() reads the next line even though the escape character for the first line has not been read by nextInt()?

    NO.

    1. next() cannot read next line, it only reads something before space.

    2. When keyboard.nextLine() executes, it consumes the "end of line" still in the buffer from the first input.

    3. when you enter a number then press Enter, keyboard.nextInt() consumes only the number, not the "end of line".

    Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.

    0 讨论(0)
提交回复
热议问题