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