Reprinted from: Scanner in Java nextint (), Next (), nextline () method Summary
Today, in the Java machine class encountered a small problem, using scanner input data, using a nextint (), once nextline (), but only received an integer. The code is as follows
Code1:
1Package CN.DX;23Import Java.util.Scanner;45PublicClassscannertest {67PublicStaticvoidMain (string[] args) {8 Scannerin =New Scanner (System.Inch);9 System.Out.println ("Please enter an integer");10WhileInch. Hasnextint ()) {11int num =Inch. Nextint ();System.Out.println ("Please enter a string");13 String str = in14 System. out.println (num=< Span style= "color: #800000;" > "+num+" ,str= "+STR); 15 System. out.println ( Please enter an integer "); 16 }17 }18}
The result of the operation is:
Please enter an integer
1231
Please enter a string
Num=1231,str=
Please enter an integer
The second parameter of type string is not read in.
See for yourself the official documentation for the next Nextint () and nextline () methods
Nextline ()
Advances this scanner past, the current line and returns the input is skipped. This method returns the rest of the "excluding" at the end of all line separator. The position is set to the beginning of the next line.
The Nextint () method reads the token of the next int type flag. But the focus does not move to the next line, still on the line. When you use the Nextline () method, all the contents of the row remaining are read, including the newline character, and then the focus moves to the beginning of the next line. Therefore, you cannot receive a variable of type string that is entered in the next line.
Then use the next () method
Code2.
1PackageCN.DX;23ImportJava.util.Scanner;45PublicClassscannertest {67PublicStaticvoidMain (string[] args) {8 Scanner in =NewScanner (system.in);9 System.out.println ("Please enter an integer"); Ten while (In.hasnextint ()) {one int num = in.nextint (); System.out.println ("Please enter a string"); String str = in.next (); System.out.println ("num=" +num+ ", str=" +str); System.out.println ("Please enter an integer"); +}
The results are correct after the operation and the results are as follows.
Please enter an integer
123
Please enter a string
Sdjakl
Num=123,str=sdjakl
Please enter an integer
213 Jdskals
Please enter a string
Num=213,str=jdskals
Please enter an integer
After the experiment, the next () method was found to receive the next string type variable as a line break or a space character.
Use of the Usedelimiter (String regex) method
Scanner class Learning in Java