Total Pageviews

Sunday, September 30, 2012

DIFFERENCE BETWEEN next() AND nextLine()

This post eradicates the confusion between next() and nextLine() and gives you a clear idea of how they work.

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by 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.

COMMON PROBLEMS WITH next() :

Consider the example,



import java.util.Scanner;

public class temp
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter string for c");
        String c=sc.next();
        System.out.println("c is "+c);
        System.out.println("enter string for d");
        String d=sc.next();
        System.out.println("d is "+d);
    }
}


OUTPUT:                             HOW IT WORKS!

enter string for c                     
abc def                                  abc |def      //cursor stays after c
c is abc
enter string for d
d is  def                                 abc def|     //cursor stays after f


Look at the output keenly. When the input for c is given as abc def, it will not read the entire input abc def. next() reads only abc and places the cursor after the alphabet c. Now, when value for d is got using next(), it will not get new value. Rather, it takes the value after the current cursor position(since the cursor is after c, def is assigned to d and the cursor stays after f).

Now, when 
 String c=sc.next() in the above program is replaced as 
 String c=sc.nextLine(), the output will be

OUTPUT:                           HOW IT WORKS!

enter string for c
ABC DEF                             ABC DEF
c is ABC DEF                       |       //cursor moves to next line
enter string for d
GHI                                       ABC DEF
d is GHI                                 GHI|    //cursor stays after I

Since nextLine() is used for reading input for c, the entire line is read and hence ABC DEF is stored in c and the cursor is placed in the next line. Now when d is read using next() or nextLine(), the cursor will be in the next line and hence the input for d is read and is placed in d (here d gets the input GHI).

So whenever next() is used, make sure nextLine() used to place the cursor in the next line. Hence the above program is also written as, 
String c=sc.next();
sc.nextLine();
String d=sc.next();

Thanks for reading my blog... :-) Comment about my blog. Stay tuned for my next post.... 


39 comments:

  1. Hi, thank you for writing such a useful blog, but im a java beginner and i dont know what does the word 'static' mean. I mean i can define it (attached to the class instead of the object) but i dont know how to use it.. can u write a blog about it please? thank you!(:

    ReplyDelete
    Replies
    1. hi buddy! thnx for ur comment... :) as u suggested me to write a blog about 'static', i've published a post about it! ;) read it! and i hope you'll understand. :) comment on my blog about it and for further queries :)

      Delete
  2. such a perfect description thats clear my doubts..thanks..

    ReplyDelete
  3. Thank you for the post. The explanation is quite clear and it helped me a lot. :)

    ReplyDelete
    Replies
    1. very nice post for next() and nextLine().

      Delete
  4. @Jennifer : Thnx for your comment :)

    ReplyDelete
  5. good descriptions. thanks!

    ReplyDelete
  6. Thanks, the write-up was very explanatory. Kip it up. God bless u

    ReplyDelete
  7. here is a problem?Can anybody explain it.

    package com.company;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Scanner;

    public class Main {

    public static void main(String[] args) {
    // write your code here
    Scanner scanner = new Scanner(System.in);
    int numOfPriceTags = scanner.nextInt();
    int numOfFruits = scanner.nextInt();
    int tagList[] = new int[102];

    int count[] = new int[102];
    List fruitList = new ArrayList();


    for (int i = 0; i < numOfPriceTags; i++){
    tagList[i] = scanner.nextInt();
    }


    for (int i = 0; i < numOfFruits; i++){

    String myFruit = scanner.next();//hre is the problem if I use here nextLine then myFruit takes "" for the first time latter it works for the latter iterations

    int p = fruitList.indexOf(myFruit);
    if (p >= 0)
    count[p]++;
    else{
    fruitList.add(myFruit);
    p = fruitList.indexOf(myFruit);
    count[p]++;
    }
    }
    Arrays.sort(count,0,(fruitList.size()));
    Arrays.sort(tagList,0,numOfPriceTags);
    int maximum = 0;
    int minimum = 0;
    int k = 0;
    for (int j = fruitList.size() - 1; j >= 0; j--){
    minimum += count[j] * tagList[k];
    k++;
    maximum += count[j] * tagList[numOfPriceTags - k];

    }
    System.out.println(minimum + " " + maximum);


    }
    }

    ReplyDelete
    Replies
    1. Just like your man explained there the nextInt() does not advance to the next line but rather it stays in as much as next() does not advance. So to make it advance put scanner.nextLine() after the nextInt(), this should work. worked like a charm on my project as well. BTW, thatnks dude for explaining the difference in plain English :)

      Delete
  8. Hi,
    Very informative, yet simple and concise. Great job. thanks.

    ReplyDelete
  9. Thnku for the perfect difference point i was looking for...and that too with example :)

    ReplyDelete
  10. thank you. Just what i was looking for. Bookmarked and saved

    ReplyDelete
  11. Thanks Great Stuff!

    ReplyDelete
  12. Thanks for the simple yet helpful explanation :)

    ReplyDelete
  13. do
    {
    System.out.println("Enter the directory:");
    p=ob.nextLine();
    System.out.println(p);
    tester[check]=p;
    check++;
    for(int i=0;i<check-1;i++)
    {
    if(tester[i].equals(p))
    {
    System.out.println("The directory is already present");
    positive=1;
    break;
    }
    else
    {positive=0;}
    }
    }while(positive!=0);


    in the next entry it is showing null pointer exceptio
    but if use next(); it executes properly but didnt read the directory with sapces in name....what to do..please help me asap..
    thanku

    ReplyDelete
    Replies
    1. Did you initialise the tester array with right amount of array size? Before assigning something to the array you need to set aside memory using new keyword. Hard to say more without seeing much of the code.

      Delete
  14. very well and clearly explained, thanks.

    ReplyDelete
  15. very well explained
    thank you :)

    ReplyDelete
  16. public static void searchString(String[] str,int i)
    {
    //String search;
    System.out.println("\n\nSearch word: ");
    String search=kb.next();
    for(int k=0; k<i; k++)
    {
    if(search.equals(str[k]))
    {
    System.out.println(str[k]+" is found at line "+ (k+1));
    break;

    }else//(!search.equals(str[k]))
    {
    System.out.println(search+" is not in the list!please try again: ");
    break;// System.out.println("\nSearch word: ");
    } // search=kb.next();

    }

    }
    im using input=scanner.nextLine() in my input Array of string,problem is
    i have to input again a string to find and compare it with my array and im using search=scanner.next()..the prob is my next() cannot read my nextLine in the array which contain a two words...i have to read my input nextLine in my array,what should i do?do i need to replace my second string next() so that it will read?ive tried it but its not working...plss help

    ReplyDelete
  17. I dont Understand A Thing. :( But I Want To.

    ReplyDelete
  18. its very helpful

    ReplyDelete
  19. Thanks a lot bro 4 u r explination.

    ReplyDelete
  20. Thanks a lot bro 4 u r explination.

    ReplyDelete
  21. Thanks a lot bro 4 u r explination.

    ReplyDelete
  22. Thanks bro I was searching out for it since a long timeand finally found it here. Fortunately before my exam.

    ReplyDelete
  23. Thanks!!! You explained it better than the so called "experts" in stackoverflow.

    ReplyDelete
  24. Im writing an assignment where i need to send email from my java program, I have everything set on my program but when i type my messeage in the program all im geting is the first word in the email i tried changing the next to nextline but when i do that it doesnt even let me type anything but send the line automatically...
    Any other guesses .... or ways ...tried with lists,arrays.
    Problem with arrays is that i cant define the lenght of the message at the start of the program and i want to send the email once i hit return aafter i complete the email.

    ReplyDelete
  25. OUTPUT: HOW IT WORKS!

    enter string for c
    abc def abc |def //cursor stays after c
    c is abc
    enter string for d
    d is def abc def| //cursor stays after f

    i think ders something missing after the the line "enter string for d"..u have not taken input frm d user n directly written d is def..i m confused whether d is def or abc def of c..just let me know what input u have given for d..

    ReplyDelete
  26. Hi thanks for you blog
    I have one query
    In this code see after integer the scanner class skips the nextline input , it does not take it
    Int g=sc.nextInt();
    String c=sc.nextLine();
    The second input will not be taken and console will skip this input
    Can u pls tell why this happens?

    ReplyDelete
  27. Hi thanks for you blog
    I have one query
    In this code see after integer the scanner class skips the nextline input , it does not take it
    Int g=sc.nextInt();
    String c=sc.nextLine();
    The second input will not be taken and console will skip this input
    Can u pls tell why this happens?

    ReplyDelete
  28. Awesome program

    ReplyDelete