A brief introduction to scanner in Java (input control for enterprise written test online programming)

Source: Internet
Author: User

Summary:

The recent enterprise online written test, found that most of the enterprise's written test platform using the game Code network (although a lot of slots), and on-line programming needs to use scanner to read the input of the program, therefore, the author on the achievements of the ancestors of scanner did a new, detailed summary. We know that Java.util.Scanner is a new feature of JAVA5, and the main function is to simplify text scanning. The most practical part of this class is to get console input, other features are very chicken, although the Java API documentation lists a number of API methods, but not very much, this is a brief description.

Copyright Notice:

This article original nerd Rico
Author Blog address: http://blog.csdn.net/justloveyou_/

One. Scan console input

This example is often used, but if you don't have a scanner, you'll know how uncomfortable it is to write. In this example, by creating a Scanner with new Scanner (system.in), the console waits for input until the hit return ends and the input is passed to Scanner as a scanned object. If you want to get the input, you only need to call Scanner's Nextline () method.

/** * Scan console input * */  Public  class testscanner {          Public Static void Main(string[] args) {Scanner s =NewScanner (system.in); System.out.println ("Please enter a string:"); while(true) {String line = S.nextline ();if(Line.equals ("Exit")) Break; System.out.println (">>>"+ line); }         } }/* Output (): Please enter the string: 234 >>>234 wer >>>wer bye >>>bye * *//
Two. The convenience of scanner

  if scanner is easy to use, it is better to say that scanner constructors support many ways, and it is convenient to build scanner objects. we can build scanner objects directly from strings (readable), input streams, files, and so on, and with scanner, we can scan the entire text piecemeal (according to regular separators) and do specific processing of the scanned results.

Three. Scanner separators

  Scanner uses spaces as delimiters to delimit text by default, but allows us to specify a new delimiter by using the method Usedelimiter (String pattern) . It is important to note that the parameter of method Usedelimiter (string pattern) is a regular expression string, and if you want to specify more than one delimiter to split, you must use the ' | ' to separate them. is as follows:

publicstaticvoidtest7() {    new Scanner("123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf    ......asdfkl    las");    s.useDelimiter(" |,|\\.");    // 将使用空格,逗号和点号来分割Scanner输入    while (s.hasNext()) {        System.out.println(s.next());    }}/* Output():         123        asdf        sd        45        789        sdf        asdfl        sdf        sdfl        asdf        asdfkl        las *///
Iv. scanner Common API profiling and usage examples

Here are a few of the most common APIs for scanner in Java:

    • delimiter ()
      Returns the Pattern that this Scanner is currently using to match the delimiter.

    • Hasnext ()
      Determines whether the next paragraph exists after the current scan position in the scanner, by default, one or more contiguous spaces as the delimiter for the segment.

    • Hasnextline ()
      Returns true if there is another row in the input of this scanner (with a carriage return as a "line break").

    • Next ()
      Finds and returns the next complete tag from this scanner (gets the input segment).

    • nextline ()
      This scanner executes the current line and returns the skipped input information (gets the input text).

Scanner Use instances (mainly for multi-line input and single line input in written-test programming):

1). Usage of Hasnextline () and nextline ()

 Public  class TestScanner1 {     Public Static void Main(string[] args) {Scanner Scanner =NewScanner (system.in);//Regular expression string        //scanner.usedelimiter ("\\*");System.out.println ("Please enter a string:");//Test1 (scanner);Test2 (scanner);//TEST3 (scanner);}/** * @description read by line (carriage return), print once per three lines in the console, three lines, block wait * @author rico * @created April 5, 2017 morning 10:31:14 * @param scanner * *     Public Static void test1(Scanner Scanner) { while(true) {//scanner continuously read from the console, blocking wait if no content            //Read in lineString S1 = Scanner.nextline ();            String s2 = scanner.nextline ();            String s3 = Scanner.nextline (); System.out.println (">>>"+ S1); System.out.println (">>>"+ s2); System.out.println (">>>"+ S3); }    }/** * @description read by line (carriage return), print once per three rows in the console, three rows, block wait (equivalent to method test1) * @author Rico * Created April 5, 2017 morning 10:31:14 * @param Scanner * *     Public Static void test2(Scanner Scanner) { while(Scanner.hasnextline ()) {//Once the console has input, scanner starts reading from the console            //Read in lineString S1 = Scanner.nextline ();            String s2 = scanner.nextline ();            String s3 = Scanner.nextline (); System.out.println (">>>"+ S1); System.out.println (">>>"+ s2); System.out.println (">>>"+ S3); }    }/** * @description read by line, read once per hit key, not ignore space * @author rico * @created April 5, 2017 Morning 10:31:14 * @param scanner * *     Public Static void test3(Scanner Scanner) { while(Scanner.hasnextline ()) {//Once the console has input, scanner starts reading from the consoleString S1 = Scanner.nextline (); System.out.println (">>>"+ S1); System.out.println (">>>"+ s1.length ()); }    }

             

2). Usage of Hasnext () and Next ()

 Public  class TestScanner1 {     Public Static void Main(string[] args) {Scanner Scanner =NewScanner (system.in);//Regular expression string        //scanner.usedelimiter ("\\*");System.out.println ("Please enter a string:");//TEST4 (scanner);TEST5 (scanner);//test6 (scanner);}/** * @description default to one or more spaces as a separator to sub-interlaced text, each three as a set of output once (not enough three to block the wait until three can be used as a group to output); In addition, a continuous input of three lines (one per line) is also possible. * @author rico * @created April 5, 2017 morning 10:37:54 * @param Scanner * *     Public Static void test4(Scanner Scanner) { while(true) {//scanner continuously read from the console, blocking wait if no contentString S1 = Scanner.next ();            String s2 = Scanner.next ();            String s3 = Scanner.next (); System.out.println (">>>"+ S1); System.out.println (">>>"+ s2); System.out.println (">>>"+ S3); }    }/** * @description with one or more spaces as a separator to sub-interlaced text, each three as a set of output once (not enough three block wait until three to be used as a group to output); In addition, a continuous input of three lines (one per line) is also possible. * @author rico * @created April 5, 2017 morning 10:49:22 * @param Scanner * *     Public Static void Test5(Scanner Scanner) { while(Scanner.hasnext ()) {//Once the console has input, scanner starts reading from the consoleString S1 = Scanner.next ();            String s2 = Scanner.next ();            String s3 = Scanner.next (); System.out.println (">>>"+ S1); System.out.println (">>>"+ s2); System.out.println (">>>"+ S3); }    }/** * @description with one or more spaces as a delimiter to separate interlaced text, output as a group (all spaces are delimiters), several outputs several * @author Rico * @created April 5, 2017 morning 10:37:54 * @param scanner * *     Public Static void Test6(Scanner Scanner) {System.out.println (Scanner.delimiter ()); while(true) {//scanner continuously read from the console, blocking wait if no contentString S1 = Scanner.next (); System.out.println (">>>"+ S1); System.out.println (">>>"+ s1.length ()); }    }

             

3). The difference between nextline () and Next ()

    • Nextline (): With carriage return as a newline flag;

    • Next (): Use one or more spaces as the segment flag, or you can use a carriage return as the segment flag (as shown).

Five. Scanner scan file input

The following example completes the use of scanner scan file input:

  Public Static void Main(string[] args)throwsFileNotFoundException {InputStream in =NewFileInputStream (NewFile ("C:\\autosubmit.java"));//create file input streamScanner s =NewScanner (in); while(S.hasnextline ())     {System.out.println (S.nextline ()); } }/* Output (): Package own;         Import Java.io.BufferedReader;         Import Java.io.BufferedWriter;         Import Java.io.InputStream;         Import Java.io.InputStreamReader;         Import Java.io.OutputStreamWriter;         Import java.net.HttpURLConnection;         Import java.net.ProtocolException;         Import Java.net.URL;         Import Com.verisign.uuid.UUID; /** * @author Wangpeng * */... *///
References:

Scanner in Java (very detailed not to see regret)

A brief introduction to scanner in Java (input control for enterprise written test online programming)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.