Use of scanner

Source: Internet
Author: User

Scanner can be implemented from string, input stream and file read, at the time of construction can choose the way you need to read, common construction method has the following 3:

    • Scanner (File source): Constructs a new Scanner , generated value that is scanned from the specified file.
    • Scanner (InputStream source): Constructs a new Scanner , generated value that is scanned from the specified input stream.
    • Scanner (string source): Constructs a new Scanner , generated value that is scanned from the specified string.

The following examples will be read from a string:

(1) Take a space as a separator to get the word (scanner the default way to split is a space):

Input: Hello world! I am coming.

Output: Hello world! I am coming.

String txt = "Hello world! I am coming. "  New  Scanner (TXT);  while (scanner.hasnext ()) {    System.out.print (+ "");}

(2) obtain each character (including spaces):

Since scanner can not do this directly, we use indirect methods. The entire string is first removed from the scanner, converted to a char array, and then processed one by one.

Input: Hello world! I am coming.

Output: H e l l o◊w o R L d! ◊i◊a m◊c o m I n G. (We use ◊ to indicate the output of the space symbol)

String txt = "Hello world! I am coming. "  New  Scanner (TXT); if (scanner.hasnextline ()) {    char[] ch =  scanner.nextline (). ToCharArray () ;      for (int i = 0; i < ch.length; i++) {        System.out.println (ch[i]);}    }

If you do not need a space, simply add a blank in the following code to judge it.

(3) Use a comma as the delimiter to get the word (set scanner by regular expression):

  Input: hello,world,i,am,coming

Output: Hello World I am coming

String txt = "hello,world,i,am,coming"new  Scanner (TXT);  Scanner.usedelimiter ("\ \,");  while (scanner.hasnext ()) {    System.out.print (+ "");}

Use of scanner

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.