In this guide, you will learn how to take 1D array and 2D array input in Java. We will be using for loop and Scanner class to accomplish this.
Java Program to take 1D array Input
import java.util.Scanner;
public class ArrayInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user to enter the array size
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
//Declare array based on entered size
int[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
// Print the array
System.out.println("Array elements:");
for (int num : array) {
System.out.print(num + " ");
}
scanner.close();
}
}
Output:
Enter the size of the array: 5
Enter the elements of the array:
10
20
30
40
50
Array elements:
10 20 30 40 50
Points to Note:
- You need to import the
java.util.Scanner
package to use the methods of Scanner class. - Always remember to use
scanner.close()
to release resources after you finish reading user input.
Java Program to take 2D array Input
The approach is similar here, however in order to take 2D array inputs, we need to use the nested for loop. Also, we need additional row and column inputs from user.
import java.util.Scanner;
public class TwoDArrayInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();
int[][] array = new int[rows][cols];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = scanner.nextInt();
}
}
// Print the array
System.out.println("Array elements:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(array[i][j] + " ");
}
// Move to the new line after printing each row
System.out.println();
}
scanner.close();
}
}
Output:
Enter the number of rows: 2
Enter the number of columns: 3
Enter the elements of the array:
10
20
30
40
50
60
Array elements:
10 20 30
40 50 60
Points to Note:
- You must ensure that the input values are either separated by spaces or newlines.
- In the above programs, we are using integer arrays, however you can modify the program to handle other types of arrays such as double or String arrays. This can be simply done by changing the data type of the array and replacing the
nextInt()
method to the appropriate methods (e.g.,nextDouble()
ornextLine()
).
Leave a Reply