![]() |
VOOZH | about |
Arrays in Java are an important data structure, and we can add elements to them by taking input from the user. There is no direct method to take input from the user, but we can use the Scanner Class or the BufferedReader class, or the InputStreamReader Class.
Approach:
Example: Taking input from the user in a one-dimensional array using the Scanner class and loops.
Output:
Explanation: In this example, first we use the Scanner class to accept user input and save the array size in the size variable. Then we make an array arr with the size s. Following that, we use a for loop to accept user input and save it in an array. Finally, we use another for loop to print the array's elements.
The Scanner class from java.util helps to take user input. We can use the Scanner class with loops to take input for individual array elements (to use this technique, we must know the length of the array).
In this example, we will understand how to take input for a two-dimensional array using the Scanner class and loops.
Approach:
Example: Taking input of Two dimenstional array from the user.
Output:
Explanation: In this example, first we use the Scanner class to accept user input of the number of rows and columns to create a 2D array. Then, we use a for loop to accept user input and save it in the 2D array. Finally, we use another for loop to print the array's elements.
We can use the BufferedReader and InputStreamReader classes to read user input in Java and use the IOException class to handle exceptions in input.
In the below example, we use the BufferedReader object to read user input and manage the input classes that even with the wrong input type the error is not thrown.
Approach:
Example: Taking input of an array from user using BufferedReader and InputStreamReader.
Output:
Explanation: In this example, we use 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 s. We handle potential input errors with try-catch blocks. Then, we initialize and populate an array with user input, and use a loop to print its elements.