First look at the explanation:
nextint (): It is reads the int value, Nextint () places the cursor in the same line after reading the I Nput.
Next (): read the input only till the space. It can ' t read 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's, it reads till the end of line \ n). Once the input is read, nextline () positions the cursor on the next line.
After reading the difference between Nextint (), Next () and nextline () is clear, I think the most error-prone is the cursor problem.
Look at the following code:
1 ImportJava.util.Scanner;2 3 Public classMaxmap {4 Public Static voidMain (string[] args) {5Scanner cin =NewScanner (system.in);6 intn =cin.nextint ();7String str =cin.nextline ();8System.out.println ("END");9 }Ten}
Results after execution:
From the execution results, it seems that the string str = Cin.nextline () is skipped directly; this line of code.
In fact, the reason is:nextint () only read the value, the remaining "\ n" has not been read, and put the cursor in the bank. Nextline () reads "\ n" and Ends (nextline () reads till the end of line \ n).
If you want to read a line after Nextint (), you have to add Cin.nextline () after Nextint (), and the code is as follows
Import Java.util.Scanner; Public class Maxmap { publicstaticvoid main (string[] args) { new Scanner (system.in); int n = cin.nextint (); Cin.nextline (); = cin.nextline (); System.out.println ("END");} }
Look at the following code:
1 ImportJava.util.Scanner;2 3 Public classMaxmap {4 Public Static voidMain (string[] args) {5Scanner cin =NewScanner (system.in);6String n =Cin.next ();7 //cin.nextline ();8String str =cin.nextline ();9System.out.println ("END");TenSystem.out.println ("Next () Read:" +n); OneSystem.out.println ("nextline () Read:" +str); A } -}
Execution Result:
Cause:next () reads only the data before the space, and the cursor points to the bank, and the back nextline () continues to read the data left behind.
To read an entire line, use Nextline ().
You can also use nextline () to read numbers, but you need to convert: Integer.parseint (Cin.nextline ()).
Note When you use Next (), Nextint () with nextline (), Next (), Nextint () tend to read part of the data (leaving "\ n" or the data after the space).
Understanding of Nextint (), Next () and nextline () in Java