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

前端 未结 3 1203
独厮守ぢ
独厮守ぢ 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.

提交回复
热议问题