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

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

提交回复
热议问题