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

后端 未结 14 2000
你的背包
你的背包 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:31

    A scanner breaks its input into tokens using a delimiter pattern, which is by default known the Whitespaces.

    Next() uses to read a single word and when it gets a white space,it stops reading and the cursor back to its original position. NextLine() while this one reads a whole word even when it meets a whitespace.the cursor stops when it finished reading and cursor backs to the end of the line. so u don't need to use a delimeter when you want to read a full word as a sentence.you just need to use NextLine().

     public static void main(String[] args) {
                // TODO code application logic here
               String str;
                Scanner input = new Scanner( System.in );
                str=input.nextLine();
                System.out.println(str);
           }
    

提交回复
热议问题