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

后端 未结 14 2019
你的背包
你的背包 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.

    0 讨论(0)
  • 2020-11-21 06:18

    I also got a problem concerning a delimiter. the question was all about inputs of

    1. enter your name.
    2. enter your age.
    3. enter your email.
    4. enter your address.

    The problem

    1. I finished successfully with name, age, and email.
    2. When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".

    The solution

    I used the delimiter for my scanner and went out successful.

    Example

     public static void main (String args[]){
         //Initialize the Scanner this way so that it delimits input using a new line character.
        Scanner s = new Scanner(System.in).useDelimiter("\n");
        System.out.println("Enter Your Name: ");
        String name = s.next();
        System.out.println("Enter Your Age: ");
        int age = s.nextInt();
        System.out.println("Enter Your E-mail: ");
        String email = s.next();
        System.out.println("Enter Your Address: ");
        String address = s.next();
    
        System.out.println("Name: "+name);
        System.out.println("Age: "+age);
        System.out.println("E-mail: "+email);
        System.out.println("Address: "+address);
    }
    
    0 讨论(0)
  • 2020-11-21 06:19

    The key point is to find where the method will stop and where the cursor will be after calling the methods.

    All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.


    For example, consider the following illustration:

    |23_24_25_26_27\n
    

    | -> the current cursor position

    _ -> whitespace

    stream -> Bold (the information got by the calling method)

    See what happens when you call these methods:

    nextInt()    
    

    read 23|_24_25_26_27\n

    nextDouble()
    

    read 23_24|_25_26_27\n

    next()
    

    read 23_24_25|_26_27\n

    nextLine()
    

    read 23_24_25_26_27\n|


    After this, the method should be called depending on your requirement.

    0 讨论(0)
  • 2020-11-21 06:20

    From JavaDoc:

    • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
    • next(): Finds and returns the next complete token from this scanner.
    • nextLine(): Advances this scanner past the current line and returns the input that was skipped.

    So in case of "small example<eol>text" next() should return "small" and nextLine() should return "small example"

    0 讨论(0)
  • 2020-11-21 06:20

    What I have noticed apart from next() scans only upto space where as nextLine() scans the entire line is that next waits till it gets a complete token where as nextLine() does not wait for complete token, when ever '\n' is obtained(i.e when you press enter key) the scanner cursor moves to the next line and returns the previous line skipped. It does not check for the whether you have given complete input or not, even it will take an empty string where as next() does not take empty string

    public class ScannerTest {
    
        public static void main(String[] args) {
    
            Scanner sc = new Scanner(System.in);
            int cases = sc.nextInt();
            String []str = new String[cases];
            for(int i=0;i<cases;i++){
                str[i]=sc.next();
            }
         }
    
    }
    

    Try this program by changing the next() and nextLine() in for loop, go on pressing '\n' that is enter key without any input, you can find that using nextLine() method it terminates after pressing given number of cases where as next() doesnot terminate untill you provide and input to it for the given number of cases.

    0 讨论(0)
  • 2020-11-21 06:22

    next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.

    nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

    For reading the entire line you can use nextLine().

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