Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

后端 未结 22 1154
北荒
北荒 2020-12-03 01:14

I\'m writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say

22条回答
  •  余生分开走
    2020-12-03 01:43

    next() will only store the input up to the first token. if there are two words "Hi there" it means there are two tokens separated by space (delimiter). Every time you call the next() method it reads only one token.

    if input is "Hi there !"

    Scanner scan = new Scanner(System.in);
    String str = scan.next()
    System.out.println(str);
    

    Output

    Hi

    So if you both the words you need to call next() again to get the next token which is inefficient for longer string input

    nextLine() on the other hand grabs the entire line that the user enters even with spaces

    Scanner scan = new Scanner(System.in);
    String str = scan.nextLine()
    System.out.println(str);
    

    Output

    Hi there !

提交回复
热议问题