"Overview
I personally prefer to use the scanner scanner when I implement the input of the character window, which is relatively simple to operate. I found that there are two ways to implement string input with scanner, one is next () and one nextline (), but what is the difference between these two methods?
"1. First, next () must be read to a valid character before it can end the input, the next () method will automatically remove The Terminator, such as the Space Bar, TAB key, or ENTER key encountered before entering a valid character, and only after entering a valid character. The next () method treats the Space bar, TAB key, or enter key after it is entered as a delimiter or terminator. Simply put, next () finds and returns the next complete tag from this scanner. The complete tag is preceded by the input information that matches the delimited pattern, so the next method cannot get a string with spaces, whereas the Nextline () method's terminator is just the ENTER key , that is, the nextline () method returns all characters before the ENTER key. It is possible to get a string with a space.
"Example
As long as the difference between the two methods, students must pay attention to the next () method and the Nextline () method of the used, as an example to illustrate:
1 ImportJava.util.Scanner;2 3 Public classTest_next {4 Public Static voidMain (string[] args) {5 String s1,s2;6Scanner scanner=NewScanner (system.in);7System.out.println ("Please enter the first string:"); 8s1=Scanner.next ();9System.out.println ("Please enter a second string:");TenS2=scanner.nextline (); OneSystem.out.println ("The string entered is:" +s1+S2); A } - -}
Test Code
1 Please enter the first string: 2 3 Please enter a second string:4
Run Results"Conclusion
Nextline () automatically reads the Enter that was removed by next () as his terminator, so there is no way to enter a value for S2 from the keyboard.
This problem is verified when other next methods such as Double nextdouble (), float nextfloat (), int nextint () are used with nextline ().
"Solution
Add a nextline () statement after each next (), Nextdouble (), www.gzlij.com (), Nextfloat (), Nextint (), and then filter out the Enter terminator that is removed by next ()
1 ImportJava.util.Scanner;2 3 Public classTest_next {4 Public Static voidMain (string[] args) {5 String s1,s2;6Scanner scanner=NewScanner (system.in);7System.out.println ("Please enter the first string:"); 8s1=Scanner.next ();9 scanner.nextline ();TenSystem.out.println ("Please enter a second string:"); OneS2=scanner.nextline (); ASystem.out.println ("The string entered is:" +s1+S2); - } - the}
Test Code
1 Please enter the first string: 2 3 Please enter the second string:4work5 The string entered is: Homework
Run Results
The difference between nextline () and Next () in Java