Obtaining Input using Scanner Class

Java programming uses different types of data values such as integer, character, float etc. These data values are entered through the console in four different ways such as assigning a value, using blueJ system to pass the argument to the mail method at the time of execution. Using Input Stream that requires a buffer for the data values to be stored through an object. Scanner classes allow a user to read various types of values. It allows inputting value from either keyboard or file. Scanner class is a predefined class defined in in java dot util package.

Along with the exception message, a program window appears and error line and error message will also be shown. To avoid the Exception, Scanner Class also provides some methods to check the next token type. Using Type checking methods of Scanner user is able to detect the end of file and can find the information about the availability of next token.

Scanner Class enables user to take input values together in sequence as string of tokens, where tokens are delimited by white space. The Scanner Class provides a method to specify separator. Closing of Scanner is necessary to enable garbage collect of Scanner object and to use its memory for other variables. Scanner can be closed using the close methods.

Scanner method that reads numeric data, throws an Input-Mismatch-Exception if next token is not a value expected by method.Some methods are used as a check to ensure that the next token to be input is of matching type or not. The method boolean has- Next-Int is used to check whether the next token can be expressed as an integer value or not.

To Access the full content, Please Purchase

  • Q1

    Name the methods that Scanner Class provides to check the type of next available token.

    Marks:1
    Answer:

    Various methods of Scanner Class to check the availability and type of next token are:

    hasNext(), hasNextInt(), hasNextDouble(), hasNextFloat() and hasNextBoolean()

    View Answer
  • Q2

    Explain the condition in which a program throws InputMismatchException.

    Marks:1
    Answer:

    If the next token available on input cannot be interpreted as the primitive type for which the method of Scanner Class is being used, then InputMismatchException is thrown by the program.

    View Answer
  • Q3

    Which package of java we need to import in our program to use Scanner Class?

    Marks:1
    Answer:

    To use Scanner, we need to import Java.util package.

    Syntax:

    import java.util.*;

    Or import java.util.Scanner;

    View Answer
  • Q4

    In which edition of java, Scanner Class was being introduced?

    Marks:1
    Answer:

    In J2SE-5.0 edition

    View Answer
  • Q5

    Which class of java allows reading input values as primitive data types from both, console and files?

    Marks:1
    Answer:

    Scanner Class

    View Answer