To get an array as input in Java, you can use a combination of the Scanner
class from the java.util
package and the nextLine()
method.
Here's an example of how to get an array as input in Java:
Scanner scanner = new Scanner(System.in); System.out.print("Enter the array: "); String input = scanner.nextLine(); String[] elements = input.split(" "); int[] numbers = new int[elements.length]; for (int i = 0; i < elements.length; i++) { numbers[i] = Integer.parseInt(elements[i]); } System.out.println("The array is: " + Arrays.toString(numbers));
In the above example, a Scanner
object is created using the Scanner()
constructor, and the nextLine()
method is used to read a line of input from the user.
The split()
method of the String
class is then used to split the input string into an array of String
s, using a space character as the delimiter.
A new integer array called numbers
is then created, with a size equal to the number of elements in the input array.
The for
loop is used to iterate over the elements
array and convert each element to an integer using the parseInt()
method of the Integer
class. The resulting integers are then stored in the numbers
array.
Finally, the toString()
method of the Arrays
class is used to convert the numbers
array to a String
representation, which is then printed to the console.
For example, if the user enters "1 2 3 4 5" as the input, the numbers
array will contain the following elements: [1, 2, 3, 4, 5].
For more information on reading input from the user in Java, you can refer to the documentation for the Scanner
class in the Java API.