In the previous sections we learned how to use split(String regex) of the String class to decompose a string, and how to use the StringTokenizer class to parse words in a string. In this section we learn how to use objects of the Scanner class to parse from strings. The data required by the program.
There are two ways to parse the data required by the program. One is to use the default delimiter tag to parse the string, and the other is to use regular expressions as delimiter tags to parse the string. In this section we will learn the first method.
To parse a string using the default delimiter tag, we need to create a Scanner object and pass the string to be parsed to the constructed object, for example:
StringNBA=ILoveThisGame;
In order to parse out the words in NBA, we can construct a Scanner object:
Scannerscanner=newScanner(NBA);
Then the scanner uses spaces as delimiters to parse the words in the string. The characteristics of the parsing operation are as follows:
1) The scanner calls the next() method to return the words in NBA in sequence. If the last word in NBA has been returned by the next() method, the scanner calls hasNext() to return false, otherwise it returns true.
2) For numeric words in the parsed string, such as 123, 1.23, etc., the scanner can use the nextInt() or nextDouble() method instead of the next() method, that is, the scanner can call the nextInt() or nextDouble() method. Convert numeric words into int or double data and return it.
3) If the word is not a numeric word, an InputMismatchException will occur when the scanner calls the nextInt() or nextDouble() method. When handling the exception, the next() method can be called to return the non-digital word.