Using the scanner class makes it easy to get the user's keyboard input, scanner is a regular expression-based text scanner that resolves basic type values and string values from files, input streams, and strings. The scanner class provides multiple constructors, with different constructors that accept files, input streams, and strings as data for parsing data from files, input streams, and strings.
Scanner mainly provides two methods to scan the input:
(1) hasnextxxx (): whether there is a next entry, where XXX can be an int, long, and so on representing the basic data type of the string. If you need to decide whether to include the next string, you can omit xxx.
(2) nextxxx (): Gets the next entry. XXX has the same meaning as in the previous method.
By default, scanner uses whitespace (including spaces, tab blanks, carriage returns) as delimiters between multiple entries. See the following program using scanner to get the user's keyboard input.
Public classtestscannerkeyboard{ Public Static voidMain (string[] args) {//system.in represents standard input, which is keyboard inputScanner sc=NewScanner (system.in); //The scanner uses the Usedelimiter (String pattern) method to set the delimiter character. The following setting uses carriage return as the delimiter,//The program reads one line at a time, regardless of whether the line contains spaces, and scanner treats it as an entry//sc.usedelimiter ("\ n"); //determine if there is a next entry while(Sc.hasnext ()) {//Output Input ItemsSYSTEM.OUT.PRINTLN ("Keyboard input content is:" +Sc.next ()); } }}
Run the above program, the program through scanner constantly reading keyboard input from the keyboard, each read to the keyboard input, directly print the input content in the console.
In fact, scanner provides two simple ways to read by line:
(1) Boolean hasnextline (): Returns whether there is a next line in the input source.
(2) string nextline (): Returns the string of the next line in the input source.
Scanner can not only get string entries, but also any type of input.
Get keyboard input using scanner