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

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

    From the documentation for Scanner:

    A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

    From the documentation for next():

    A complete token is preceded and followed by input that matches the delimiter pattern.

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

    In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.

    Lets have a look at following snippet of code

        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        String[] s = new String[t];
    
        for (int i = 0; i < t; i++) {
            s[i] = in.next();
        }
    

    when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as

    Input as :- abcd abcd or

    Input as :-

    abcd

    abcd

    Output will be like abcd

    abcd

    But if in same code we replace next() method by nextLine()

        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        String[] s = new String[t];
    
        for (int i = 0; i < t; i++) {
            s[i] = in.nextLine();
        }
    

    Then if you enter input on prompt as - abcd abcd

    Output is :-

    abcd abcd

    and if you enter the input on prompt as abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)

    Output is:-

    abcd

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