Write Java code for implementing arrays that accepts user inputs and then displays them. Take different arrays like this: stringArray, integerArray, doubleArray.
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();
}
}
Comments
Leave a comment