How to use BufferedReader and InputStreamReader Class In Java
We can use the BufferedReader object to read user input in Java and use the IOException Class to handle exceptions in input.
In the program below we use the BufferedReader object to read user input and manage the input classes such that even with the wrong input type the error is not thrown.
Example:
Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // Take the array size from the user System.out.println( "Enter the size of the array: " ); int arr_size = 0 ; try { arr_size = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { System.out.println( "Invalid input for array size. Please enter a valid integer." ); return ; } // Initialize the array's // size using user input int [] arr = new int [arr_size]; // Take user elements for the array System.out.println( "Enter the elements of the array: " ); for ( int i = 0 ; i < arr_size; i++) { try { arr[i] = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { System.out.println( "Invalid input for array element. Please enter a valid integer." ); return ; } } System.out.println( "The elements of the array are: " ); for ( int i = 0 ; i < arr_size; i++) { // prints the elements of an array System.out.print(arr[i] + " " ); } // Close the BufferedReader br.close(); } } |
Output:
Explanation of the above Program:
In this example, we utilize BufferedReader and InputStreamReader classes to capture user input and construct an array based on the specified size. We make an array arr with the size ‘arr_size’.
We handle potential input errors gracefully with try-catch blocks. Following that, we initialize and populate an array with user input, and use a loop to print its elements.
How to Take Array Input From User in Java
There is no direct method to take array input in Java from the user. In this article, we will discuss two methods to take array input in Java. But first, let’s briefly discuss arrays in Java and how they differ from other programming languages.
Array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Some important points about Java arrays are:
- Arrays are dynamically allocated.
- Arrays are stored in contiguous memory [consecutive memory locations].
- Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.
- A Java array variable can also be declared like other variables with [] after the data type.
- The variables in the array are ordered, and each has an index beginning with 0.
Read More: Arrays in Java