Answer to Question #261122 in Java | JSP | JSF for hassan

Question #261122

 Write Java code for implementing arrays that accepts user inputs and then displays them. Take different arrays like this: stringArray, integerArray, doubleArray.



1
Expert's answer
2021-11-04T16:26:09-0400
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();
  }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS