Saturday, 2 July 2016

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?
Read more »

No comments:

Post a Comment