0

can anyone explain to me what exactly nextLine method mean in java ? how does it work ??? and #why java skipped nextLine() if nextInt() method invoked before it as the code below??!!

  int i;
  String s;
  Scanner sc=new Scanner(System.in);
  i=sc.nextInt(); //enter 5

  s=sc.nextLine(); // enter helloWorld
  System.out.println(i+"  **  "+s);

that will print

5  **

i have tried alot of code ... and i have tried to write next() method instead of nextLine() method ...and its work ...the problem just in nextLine() method

OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
Rand
  • 101
  • 8
  • So... what's the issue? Do you want a link to documentation you should really learn to Google yourself? Do you want to [edit] your question to include a [mcve] and ask about an error? – Fund Monica's Lawsuit Oct 09 '16 at 21:29
  • It works as expected. It will read up to the next newline character – OneCricketeer Oct 09 '16 at 21:29
  • Text is simply collection of characters. We describe line as text between characters which are considered as line separators like `\r` `\n` like `"this is line 1\r\nthis is line 2"`. Problem with `nextInt` is that it doesn't *consume* these line separators, while `nextLine` tries to find characters *until* first line separators it will see (or until end of stream). So since `nextLine` didn't consume those `\r\n` `nextLine` finds them immediately, which means it returns *empty* String `""`. – Pshemo Oct 09 '16 at 21:33
  • nextLine() give you the rest of the line, after you called nextInt() you hit enter so nextLine() reads the rest of the line after the number you typed. – Peter Lawrey Oct 09 '16 at 21:36
  • Oh, important thing is that when you are asking in console user for any data, user must press enter/return key to confirm its imput which is adding these line separators which cause this problem with `nextLine()`. – Pshemo Oct 09 '16 at 21:36

0 Answers0