Java Scanner class and Exception catchers Try, Catch, Finally

24blognews
2 min readNov 27, 2023

--

Scanner class in java comes with java.util package, facilitates reading data value input by the user. Data value can be of different formats. So, to read the input, several methods as per the type of data are defined inside scanner class. Below is the list of methods used with an instance of Scanner Class Object.

Method Description

nextBoolean() A boolean value gets read

nextByte() An input byte data gets read

nextDouble() An input double data gets read

nextFloat() An input float data gets read

nextInt() An input Integer data gets read

nextLine() An input float data gets read

nextLong() An long byte data gets read

nextShort() An input short data gets read

When an input data gets read, with the datatype read method, value is validated, and when input value data type validation fails, error or exception is thrown or generated by the java compiler.

In the code an instance of Scanner class object is created with name myScannerClassObject, so to use the class methods.

To maintain code stability exception catcher’s try and catch are defined. In the example below three different user input data type value are read by the scanner class methods. nextLine(), .nxtInt() and .nextDouble(). Whenever any input data mismatches its field data type, exception gets throwed, and try and catch works on the exception. In cases of exceptions, finally keyword command still gets executed regardless try and catch exception catcher’s work.

import java.util.Scanner; // bringing scanner class interface

class narayan {

public static void main(String[] args) {

try{

Scanner myScannerClassObject = new Scanner(System.in);

System.out.println(“Enter username”);

String stringVariable = myScannerClassObject.nextLine(); // Read user input

Integer myInt = myScannerClassObject.nextInt();

Double myDouble = myScannerClassObject.nextDouble();

System.out.println(“Username is: “ + stringVariable); // Output user input

System.out.println(“Roll No. is: “ + myInt); // Output user input

System.out.println(“Average Speed is: “ + myDouble + “m/s”); // Output user input

} catch (Exception e) {

System.out.println(“Data type mismatch”);

} finally {

System.out.println(“type correct data type value”);

}

}

}

When the code is compiled three user inputs are asked, go ahead and compile it. And visit below link for more practice tutorials.

https://www.roseindia.net/java/ #javaexceptions #javascannerclass #coding

--

--