Java Array multidimensional Arrays initialize arrays with input values.

Description

Java Array multidimensional Arrays initialize arrays with input values.

import java.util.Arrays;
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    int[][] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

    System.out.println(Arrays.deepToString(matrix));
    //from  w w  w.  j a v a2s .c  om
    java.util.Scanner input = new Scanner(System.in);
    System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: ");
    for (int row = 0; row < matrix.length; row++) {
      for (int column = 0; column < matrix[row].length; column++) {
        matrix[row][column] = input.nextInt();
      }
    }
    input.close();

    System.out.println(Arrays.deepToString(matrix));
  }
}
 
public class Main
{
   // create and output two-dimensional arrays
   public static void main(String[] args)
   {/* w  w w  .j  a v  a  2s.com*/
      int[][] array1 = {{1, 2, 3}, {4, 5, 6}};        
      int[][] array2 = {{1, 2}, {3}, {4, 5, 6}}; 
    
      System.out.println("Values in array1 by row are");
      outputArray(array1); // displays array1 by row
       
      System.out.printf("%nValues in array2 by row are%n");
      outputArray(array2); // displays array2 by row
   } 
    
   // output rows and columns of a two-dimensional array
   public static void outputArray(int[][] array)
   {
      // loop through array's rows
      for (int row = 0; row < array.length; row++) 
      {
         // loop through columns of current row
         for (int column = 0; column < array[row].length; column++)
            System.out.printf("%d  ", array[row][column]);
    
         System.out.println();
      } 
   } 
}



PreviousNext

Related