-3

I used the current code to check the difference between nextLine() and next()

Scanner sc = new Scanner(System.in);
System.out.print("Add a String\n");
String string1 = sc.next(); 
System.out.println(string1);
String string2=sc.nextLine();
System.out.println(string2);

when I was executing the program, it displayed "Add a string" for the first entry and I was able to enter the first string, but I was not able to enter the second string.

I want to know why and how to fix that.

David Buck
  • 3,439
  • 29
  • 24
  • 31
Novice BL
  • 1
  • 2
  • 4
    Does this answer your question? [What's the difference between next() and nextLine() methods from Scanner class?](https://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-scanner-class) – Vignesh_A Oct 18 '20 at 10:20

3 Answers3

0

From the Scanner documentation:

String nextLine(): Advances this scanner past the current line and returns the input that was skipped.

String next(): Finds and returns the next complete token from this scanner.

eskapynk
  • 29
  • 2
0
sc.nextLine()

will block until you enter a line seperator (= hit the enter-button) and then return everything entered excluding the line seperator

see https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

Andi
  • 152
  • 9
0

As per javadocs:

next() - Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

All whitespace characters are considered as delimiters, so the string: "i add a string" for multiple calls on sc.next() will be split into: "i", "add", "a", "string".

nextLine() - Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end.

sc.nextLine() will return the whole string up to the end of the current line. But, not the rest part, this means that if a previous call on sc read a couple of characters, it will continue from there up to the end of the line.

So, for the string: "i add a string", next() reads "i", nextLine() reads "add a string". ("i" was read from next())

More info here: