Scanner Class in Java

Scanner Class in Java


Scanner Class In Java Notes

Scanner Class in Java

A Scanner class breaks its input into tokens using a delimiter pattern, which by default matches white space. The resulting tokens may then be converted into values of different types using the various next methods.

The Scanner class is a class in java.util package, which allows the user to read values of various types. Scanner class is used to read in numeric values from either the keyboard or file without having to convert them from strings and determine if there are more values to be read.

Methods of Scanner Class

  1. int nextInt() Returns the next token as an int. If the next token is not an integer, InputMismatchException is thrown.
  2. long nextLong() Returns the next token as a long. If the next token is not an integer, InputMismatchException is thrown.
  3. float nextFloat() Returns the next token as a float. If the next token is not a float or is out of range, InputMismatchException is thrown.
  4. double nextDouble() Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException is thrown.
  5. String next() Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break. If no token exists, NoSuchElementException is thrown.
  6. String nextLine() Returns the rest of the current line, excluding any line separator at the end.
  7. void close() Closes the scanner.