- How to take array input from command line in Java ? Scanner Example
- Java Program to take array input from User
- Program to take an array as input from user in Java
- Important points
- Как заполнить массив в java с клавиатуры
- How to read data from scanner to an array in java?
- Example
- Output
- Java array from scanner
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
How to take array input from command line in Java ? 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 the 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 the nextInt() or nextDouble() method of the Scanner class.
Some programmers may still be 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.
And, If you are new to the Java world then I also recommend you go through these free Java Programming courses to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
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 you, 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(); > > Now, let's see the output of this program to understand how to take array as input from command line in Java: 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 leaks in Java, you can also see these Java programming courses to learn more about why you should close readers and stream once you are done using them.
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 the 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 the Scanner class which you should remember while using it in the Java program:
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 arrays. Since Scanner allows you to read an int , String , double , float , byte, and long you can create those types of array. There is no method to read characters but you can read the character as a String to create a char array.
Как заполнить массив в java с клавиатуры
Для ввода массива с клавиатуры в Java можно использовать класс Scanner из стандартной библиотеки Java . Например, чтобы ввести массив целых чисел с клавиатуры, можно использовать следующий код:
import java.util.Scanner; public class Main public static void main(String[] args) Scanner scanner = new Scanner(System.in); System.out.print("Введите длину массива: "); int length = scanner.nextInt(); int[] array = new int[length]; System.out.println("Введите элементы массива:"); for (int i = 0; i length; i++) array[i] = scanner.nextInt(); > System.out.println("Массив: " + Arrays.toString(array)); > >
- В этом примере мы создали объект класса Scanner , который позволяет считывать данные из стандартного потока ввода (клавиатуры).
- Затем мы запросили у пользователя длину массива и создали массив нужного размера.
- После этого мы в цикле заполняем массив элементами, вводимыми с клавиатуры, с помощью метода nextInt() объекта Scanner.
- Наконец, мы выводим полученный массив на экран с помощью метода toString() класса Arrays
Для ввода массива других типов данных нужно использовать соответствующие методы класса Scanner , например, nextDouble() для ввода массива вещественных чисел.
How to read data from scanner to an array in java?
The Scanner class of the java.util package gives you methods like nextInt(), nextByte(), nextFloat() etc. to read data from keyboard. To read an element of an array uses these methods in a for loop:
Example
import java.util.Arrays; import java.util.Scanner; public class ReadingWithScanner < public static void main(String args[]) < Scanner s = new Scanner(System.in); System.out.println("Enter the length of the array:"); int length = s.nextInt(); int [] myArray = new int[length]; System.out.println("Enter the elements of the array:"); for(int i=0; iSystem.out.println(Arrays.toString(myArray)); > >
Output
Enter the length of the array: 5 Enter the elements of the array: 25 56 48 45 44 [25, 56, 48, 45, 44]
I love programming (: That’s all I know
- Related Articles
- How to read a single character using Scanner class in Java?
- How to switch data from an array to array list in java?
- How to read data from .csv file in Java?
- How to read data from JSON array using JavaScript?
- How to read/write data from/to .properties file in Java?
- How to read the data from a file in Java?
- How to read data in from a file to String using java?
- How to print data of specific element from an array in java?
- How to read a 2d array from a file in java?
- How to read contents of a file using Scanner class?
- How to read data from user using the Console class in Java?
- How to read data from all files in a directory using Java?
- How to read the data from a properties file in Java?\n
- How to read the data from a CSV file in Java?\n
- How to read data from EEPROM in Arduino?
Java array from scanner
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter