QUESTIONS & ANSWERS
JAVA
Explain each function of Scanner Class to retrieve the tokens.
The Scanner class in Java is used to read input from various sources such as files, input streams, and strings. It provides a set of functions to retrieve tokens from the input source. Here are the different functions of Scanner class to retrieve tokens:
-
next()
: This function reads the next token from the input source and returns it as a string. It ignores any leading whitespace and stops reading at the first whitespace character. -
nextLine()
: This function reads the next line of text from the input source and returns it as a string. It includes any whitespace characters and stops reading at the end of the line. -
nextInt()
: This function reads the next token from the input source and tries to parse it as an integer. If the token cannot be parsed as an integer, it throws an InputMismatchException. -
nextDouble()
: This function reads the next token from the input source and tries to parse it as a double. If the token cannot be parsed as a double, it throws an InputMismatchException. -
nextBoolean()
: This function reads the next token from the input source and tries to parse it as a boolean. It returns true if the token is "true" (case insensitive) and false if the token is "false" (case insensitive). If the token cannot be parsed as a boolean, it throws an InputMismatchException. -
nextByte()
: This function reads the next token from the input source and tries to parse it as a byte. If the token cannot be parsed as a byte, it throws an InputMismatchException. -
nextShort()
: This function reads the next token from the input source and tries to parse it as a short. If the token cannot be parsed as a short, it throws an InputMismatchException. -
nextLong()
: This function reads the next token from the input source and tries to parse it as a long. If the token cannot be parsed as a long, it throws an InputMismatchException.
These functions can be used to retrieve tokens from different types of input sources and parse them into different data types as needed.