- 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
- How to input in java array
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Take Array Input in Java
- Java Program to Get Array Input From End-user
- Passing Array as Argument
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.
How to input in java array
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
Take Array Input in Java
Take Array Input in Java | Array Programs in Java – 2 | In the previous Java program, we have seen how to find the length of an array in Java. Now in this post, we will see how to take array input in Java? Prerequisite:- Array in Java
We can get array input in Java from the end-user or from a method. First, we will develop a program to get array input from the end-user through the keyboard, and later we will develop a Java program to take an array as an argument.
Java Program to Get Array Input From End-user
To get input from the end-user we can use the Scanner class. For this, first, we need to create an object for the Scanner class and call the appropriate method to read the input value.
import java.util.Scanner; public class Test < public static void main(String[] args) < // Scanner class object to read input Scanner scan = new Scanner(System.in); // declaring and creating array objects int[] arr = new int[5]; // displaying default values System.out.println("Default values of array:"); for (int i=0; i < arr.length; i++) < System.out.print(arr[i]+"\t"); >// initializing array System.out.println("\n\n***Initializing Array***"); System.out.println("Enter "+ arr.length + " integer values:"); for(int i=0; i < arr.length; i++) < // read input arr[i] = scan.nextInt(); >System.out.println("***Initialization completed***\n"); //displaying initialized values System.out.println("Array elements are:"); for (int i=0; i < arr.length; i++) < System.out.print(arr[i]+"\t"); >> >
Default values of array:
0 0 0 0 0
***Initializing Array***
Enter 5 integer values:
10
20
30
40
50
***Initialization completed***
Array elements are:
10 20 30 40 50
In this array program, array elements are not initialized with explicit values, they are initialized with a default value. The default value of the int data type is 0, so they are initialized with 0. Later we updated array elements with values 10, 20, 30, 40, and 50.
Passing Array as Argument
To pass array object as an argument the method parameters must be the passes array object type or its superclass type.
Program2:- Develop a Java program to define a method to receive the number of integer values dynamically from another method as an argument in this method. Read and display all values.
public class ArrayMethod < public static void main(String[] args) < int[] array=; display(array); > static void display(int[] a) < for(int i=0; i< a.length; i++) < System.out.print(a[i]+"\t"); >> >
Program3: Develop a program to find the sum of array elements. Display array elements, and use a user-defined method for calculating the sum of array elements.
public class ArraySum < // main method public static void main(String[] args) < // array with explicit values int[] array = ; int sum = 0; sum = sumOfArrayElements(array); System.out.println("\nSum of" + " array elements: " + sum); > // method to display array elements // and calculate sum static int sumOfArrayElements(int[] a) < int sum=0; // display array and calculate sum for(int i=0; i< a.length; i++)< System.out.print(a[i]+"\t"); sum += a[i]; >return sum; > >
5 15 25 35 45 55 65
Sum of array elements: 245
When we pass an array object as an argument into a method, and if we modify array object values with method parameters then the modification is effected to the original referenced variable.
Q) Guess the output of the below program?
public class Array < public static void main(String[] args) < int[] a = ; m1(a); for(int i=0; i < a.length; i++)< System.out.print(a[i]+"\t"); >> static void m1(int[] ia) < ia[1] = 4; ia[2] = 5; >>
You may think the output 10, 20, 30, and 40 but it is the wrong output. The actual output is- 10 4 5 40; The Java language uses pass by reference not the pass by value. That’s why we get this output.
Program description:- Develop a Java program to read an array of double data-type values from the end-user. Pass this array to a method to calculate the sum of the array elements. Also, pass this array to a method to display the array elements and later display the sum of the array elements.
import java.util.Scanner; class Test < // method to display array elements public static void display(double[] a) < for (int i=0; i < a.length; i++) < System.out.print(a[i]+"\t"); >> // method to find sum of array elements public static double sumOfArray(double[] a) < double sum = 0.0; for (int i=0; i < a.length; i++) < sum += a[i]; >return sum; > // main method public static void main(String[] args) < // Scanner class object to read input Scanner scan = new Scanner(System.in); // declare variables int n = 0; double[] arr = null; double sum = 0.0; // read number of elements System.out.print("How many numbers" + " you want to enter:: "); n = scan.nextInt(); // declare array arr = new double[n]; // initializing array System.out.println("Enter "+ arr.length + " numbers:"); for(int i=0; i < arr.length; i++) < // read input arr[i] = scan.nextDouble(); >// pass array to find sum sum = sumOfArray(arr); // display array System.out.println("Array elements are:"); display(arr); // display sum value System.out.println("\nSum = " + sum); > >
How many numbers you want to enter:: 5
Enter 5 numbers:
12.5
19.8
10
20
58
Array elements are:
12.5 19.8 10.0 20.0 58.0
Sum = 120.3
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!