Using Scanner to Read User’s InputA common use of Scanner is reading input from the user in command-line environment, as its nextXXX() methods are more convenient than the Console’s readLine() method which returns only String. Since the Scanner class implements the AutoCloseable interface, we can use it with the try-with-resources structure to let the compiler adds the code to close it implicitly.Next, we show you various examples using the Scanner class. * Closing the Scanner:We should close the Scanner after use by invoking its close()method. This can be useful in as we don’t want to parse a certain input. It’s also possible to use a regular expression as a delimiter for more advanced parsing.The useLocale(Locale) method specifies a locale which is different than the system’s default locale.The skip(String pattern) method skips an input that matches the pattern. These methods throw InputMismatchException if the next token cannot be converted to the specified type throw NoSuchElementException if the input is exhausted and throw IllegalStateException if the scanner is closed.The useDelimiter(String pattern)method specifies a delimiter different than the default whitespace. These methods throw IllegalStateException if the scanner is closed.The next()method returns the next token as a String.The nextXXX()method return the next token as a value of the specified type. the hasNextInt()method returns true if the next token can be converted to an integer number. The hasNext() method returns true if the scanner has another token in its input.The hasNextXXX() method returns true if the next token can be converted to the specified type, e.g. We can also use different delimiter and locale. * Scanner’s Primary Methods:The Scanner class provides various methods for reading tokens from an input source. Note that these constructors throw FileNotFoundException if the specified file does not exist, or IllegalArgumentException if the specified charset is not found. Scanner(String source): constructs a Scanner from a String.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |