How to take array input in Java using Scanner - Example

There is no direct way to take array input in Java using Scanner or any other utility, but it's pretty easy to achieve the same by using standard Scanner methods and asking some questions to the user. For example, if you want to take a one-dimensional array of String as input then you can first ask the user about the length of the array and then you can use a for loop to retrieve that many elements from user and store them in an array. You can use the next() to take a String input from the user. Similarly, if you need to take an integer array or double array, you can use nextInt() or nextDouble() method of Scanner class. Some programmer may still stuck and ask, how about taking a two-dimensional array as input? Well isn't that pretty easy by applying some maths?

If you look, a two-dimensional array is like a matrix, You need both numbers of rows and columns to create and populate the two-dimensional array in Java. Just ask the user and then read subsequent input to store in the 2-dimensional array as row by row. Don't worry, in this article, I'll show you a couple of examples about how to take array input in Java using Scanner.


Java Program to take array input from User

Here is our sample Java program to demonstrate how to take an array as input from the user. As I told, there is no direct way but you can use a for loop to read user input and save them into the array. By using this technique you can also take a two-dimensional array as input.

Depending on which type of array you are taking as input e.g. String or int or any other array, you need to use the next() or nextInt() method to read a value from the command prompt. You can then save this value into array by assigning to respective index e.g. input[i] = sc.next().


Program to take an array as input from user in Java

import java.util.Arrays;
import java.util.Scanner;

/*
 * Java Program to take array input from the user using Scanner.
 */

public class ArrayInputDemo {

  public static void main(String[] args) {

    // taking String array input from user
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter length of String array");
    int length = sc.nextInt();

    // create a String array to save user input
    String[] input = new String[length];

    // loop over array to save user input
    System.out.println("Please enter array elements");
    for (int i = 0; i < length; i++) {
      String userInput = sc.next();
      input[i] = userInput;
    }

    System.out.println("The String array input from user is : ");
    System.out.println(Arrays.toString(input));

    // saving user input inside a 2D array in Java
    System.out.println("Please enter number of rows and columns of 2D array");
    int rows = sc.nextInt();
    int columns = sc.nextInt();

    int[][] data = new int[rows][columns];
    System.out.println("Please enter array elements row by row");

    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < columns; j++) {
        int value = sc.nextInt();
        data[i][j] = value;
      }
    }

    System.out.println("The 2d int array input from user is : ");
    System.out.println(Arrays.deepToString(data));

    sc.close();
  }
}
Output
Please enter length of String array
3
Please enter array elements
Java
C++
Ruby
The String array input from user is : 
[Java, C++, Ruby]
Please enter number of rows and columns of 2D array
2
3
Please enter array elements row by row
1
2
3
4
5
6
The 2d int array input from user is : 
[[1, 2, 3], [4, 5, 6]]


You can see that we have successfully taken array input from the user, both String and integer array, and both one and a two-dimensional array.

Don't forget to close the Scanner once you have done to prevent resource leak in Java, see Core Java for the Impatient by Cay S. Horstmann to learn more about why you should close readers and stream once you are done using them.

How to take array as input from user in Java using Scanner


Important points

1) Use next() to read String instead of nextLine()which is used to read the entire line. This is useful when you read a file line by line in Java as shown here

2) I have used the Arrays.toString() and Arrays.deepToString() to display actual elements of the array into the console because array in Java doesn't override the toString() method and directly printing them will not be very meaningful as discussed here.

3) If you want to learn more about such fundamentals of Java Programming language, I strongly suggest reading the Core Java Volume 1 - Fundamentals by Cay S. Horstmann. One of the best and most readable book on core Java at the moment. It also covers Java SE 8.

Finally, here are some important points about Scanner class which you should remember while using it in Java program:

How to take array as input from command prompt in Java


That's all about how to take array input in Java using Scanner class. It's a simple technique to save input from the user into an array and can be used to save input in both one and multi-dimensional array. Since Scanner allows you to read an int, String, double, float, byte and long you can create those type of array. There is no method to read character but you can read the character as String to create a char array.

1 comment :

Post a Comment