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

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

    The basic difference is next() is used for gettting the input till the delimiter is encountered(By default it is whitespace,but you can also change it) and return the token which you have entered.The cursor then remains on the Same line.Whereas in nextLine() it scans the input till we hit enter button and return the whole thing and places the cursor in the next line. **

            Scanner sc=new Scanner(System.in);
            String s[]=new String[2];
            for(int i=0;i<2;i++){
                s[i]=sc.next();
            }
            for(int j=0;j<2;j++)
            {
                System.out.println("The string at position "+j+ " is "+s[j]);
            }
    

    **

    Try running this code by giving Input as "Hello World".The scanner reads the input till 'o' and then a delimiter occurs.so s[0] will be "Hello" and cursor will be pointing to the next position after delimiter(that is 'W' in our case),and when s[1] is read it scans the "World" and return it to s[1] as the next complete token(by definition of Scanner).If we use nextLine() instead,it will read the "Hello World" fully and also more till we hit the enter button and store it in s[0]. We may give another string also by using nextLine(). I recommend you to try using this example and more and ask for any clarification.

提交回复
热议问题