Вывод трехмерного массива java

3D Array in Java

3D Array in Java | A three-dimensional array is a collection of 2D arrays. It is specified by using three subscripts: block size, row size, and column size. More dimensions in an array mean more data can be stored in that array. Let us discuss points related to the 3-dimensional array in Java.

Declare 3D Array in Java

Before using any variable we must declare the variable. The full syntax to declare the 3 dimensional array is:-

In this syntax the accessibility modifier and execution level modifiers are optional, but the remaining are manadatory. Example of declaring three dimensional array:-

int[][][] arr1;
float[][][] n1;
public static int[][][] arr2;
public static float[][][] n2;

The dimension or level is represented by [] . Therefore the three-dimensional array will contain [][][] . The single-dimensional array contain [] , the two-dimensional array contain [][] , and so on.

Rules for declaring 3 dimensional array in Java

1) [][][] can’t be placed before data type, else it will give the compile-time error: illegal start of expression . The [][][] can be placed after the data type, before variable-name, or after variable-name.

int[][][] i1; // valid int [][][] i2; // valid int [][][]i3; // valid int i4[][][]; // valid int[][] []i5; // valid int[][] i6[]; // valid int[] [][]i7; // valid int[] []i8[]; // valid int[] i9[][]; // valid /* []int[][] i10; // error [][]int i11[]; // error [][][]int i12; // error */

These examples many forms are valid but they can create confusion. Therefore it is recommended to use [][][] after data type or variable name. Example:- int[][][] i1; or int i3[][][];

2) Size can’t be mentioned in the declaration part. Violation of this rule leads to a compile-time error: not a statement .

int[2][2][2] i1; // error int[][3][3] i2; // error int[][][4] i3; // error
  • int i[], j[][][]; // i is of type int[] but j is of int[][][]
  • int[][][] i, j; // both i and j are of type int[][][]
  • int[][] i[], j; // i is of type int[][][] , but j is of type int[][]
  • int[] i[][], j; // i is of type int[][][] , and j is of type int[]

Initialize 3 Dimensional Array in Java

Similar to single dimensional array the 3D array also can be Initialized in three ways,

1) Three dimensional array Initialization with explicit values.

int[][][] arr = ,,>,,,>>; public static int[][][] arr1 = ,,>,,,>>;

In this way of array Initialization, the array is declared and initialized in the same line because array constants can only be used in initializers. The accessibility modifier and execution level modifiers are optional. We can use this approach only if the values are known at the time of three-dimensional array declaration.

3D Array in Java

2) Three-dimensional array Initialization with default values or without explicit values.

// decalre a 3D array int[][][] arr = null; // create array with default values arr = new int[2][3][2];

Since it is an array of int data type and the default value for int is 0, therefore this array is intialized with 0. Later we can update the values by accessing the array elements.

Читайте также:  To view all html codes

Instead of two lines, we can declare and create an array within a single line. Example:- int[][][] arr = new int[2][3][2];

  • One grand-parent array is created with 2 locations
  • The two-parent array is created with 3 locations
  • Three child arrays are created with 2 locations

grand-parent and parent array size gives below two information,

In this way of 3D array creation in Java, the base (grand-parent) array size is mandatory where as parent and child array size is optional. We can declare them later.

int[][][] a1 = new int[2][][]; // valid int[][][] a2 = new int[][2][]; // error int[][][] a3 = new int[][][2]; // error int[][][] a4 = new int[2][2][]; // valid int[][][] a5 = new int[2][2][2]; // valid

3) In the third way we can create it as an anonymous array. Example:-

// decalre a 3D array int[][][] arr = null; // create array with explicit values arr = new int[][][] ,,>,,,>>;

Advantage of this approach:- While 3D array Initialization with explicit values (1st way), we must declare and initialize the array in a single line else we will get error. But using this approach we can declare and initialize with explicit value at different lines.

Access Array Elements

Three dimensional array creation,

Accessing and initializing above array,

We can declare and initialize in a single line,

Three dimensional array in Java

Java 3D Array Length

To access the length or size of grand-parent use .length, example:- arr.length . Similarly to access the parent length use [index].length, example:- arr[0].length, arr[1].length . And to access the child array size use [index1][index2].length. Now let us see it through a Java program,

Java program to find the length or size of 3D array,

public class ThreeDArray < public static void main(String[] args) < // 3D array int[][][] arr = ,,>,,,>>; System.out.println("Grandparent size = " + arr.length); System.out.println("Parent-1 size = " + arr[0].length); System.out.println( "Child-1 of Parent-1 size = " + arr[0][0].length); > >

Grandparent size = 2
Parent-1 size = 3
Child-1 of Parent-1 size = 2

In this example, all parents have size 3 and all childs are having similar size=2. But for Jagged array the size can vary.

How to Print 3D Array in Java

To print 3 dimensional array in Java, we can use loops or pre-defined function. The loops can be for loop, for-each loop, while loop, or do-while loop. Let us demonstrate for loop and for-each loop. While using for loop we will use length property.

Java Program to print three dimensional array using for loop

public class ThreeDArray < public static void main(String[] args) < // 3D array 2x3x2 int[][][] arr = ,,>,,,>>; // displaying three dimension array in Java // using for loop and length property for(int i=0; i < arr.length; i++)< for(int j=0; j < arr[i].length; j++)< for(int k=0; k < arr[i][j].length; k++)< System.out.print( arr[i][j][k] + " "); >System.out.println(); // new line > System.out.println(); // new line > > >

Java Program to Print three dimensional array using for-each loop

public class ThreeDArray < public static void main(String[] args) < // 3D array 2x3x2 int[][][] arr = ,,>,,,>>; // displaying three dimensional array in Java using // for-each loop for(int[][] i: arr) < for(int[] j : i)< for(int k: j)< System.out.print(k + " "); >System.out.println(); // new line > System.out.println(); // new line > > >

In addition to this, we have the Arrays class defined in java.util package which contains lots of pre-defined methods related to the array. In this class deepToString() method is given to display the multidimensional array.

Читайте также:  Bool to word python

Java Program to display three dimensional array using Arrays.deepToString() method

import java.util.Arrays; public class ThreeDArray < public static void main(String[] args) < // 3D array 2x3x2 int[][][] arr = ,,>,,,>>; // displaying three dimensional array in Java using // Arrays.deepToString() System.out.println(Arrays.deepToString(arr)); > >

Java Program to Take Input from user for 3 Dimensional Array

Let us devlop a Java program to demonstrate how to take input from the end-user. 3d array in Java examples to take array and display.

import java.util.Scanner; public class ThreeDArray < public static void main(String[] args) < // declare variables int[][][] arr = null; // 3D array int grandParentSize = 0; int parentSize = 0; int childSize = 0; Scanner scan = null; // create Scanner class object to read input scan = new Scanner(System.in); // Take sizes from the user System.out.print( "Enter grandparent parent and child size = "); grandParentSize = scan.nextInt(); parentSize = scan.nextInt(); childSize = scan.nextInt(); // create 3D array with given sizes arr = new int[grandParentSize][parentSize][childSize]; // read input value for the 3D array System.out.println("Enter array elements: "); for(int i=0; i> > // displaying three dimensional array in Java using // for-each loop System.out.println("\nEntered 3D array,"); for(int[][] i: arr) < for(int[] j : i)< for(int k: j)< System.out.print(k + " "); >System.out.println(); // new line > System.out.println(); // new line > // close Scanner scan.close(); > >

Enter grandparent parent and child size = 2 2 2
Enter array elements:
Element[0][0][0]: 10
Element[0][0][1]: 20
Element[0][1][0]: 35
Element[0][1][1]: 45
Element[1][0][0]: 9
Element[1][0][1]: 18
Element[1][1][0]: 90
Element[1][1][1]: 81

Entered 3D array,
10 20
35 45

Pass and Return 3 Dimensional Array

Like a single-dimensional array, the three-dimensional array in Java also can be passed to a method and returned from a method. We will develop a program that takes input from another method (i.e. returning 3D array) and pass it to another method to display.

public class ThreeDArray < public static void main(String[] args) < // declare variables int[][][] arr = null; // 3D array // create 3D array with 2x2x2 size arr = new int[2][2][2]; // take input for 3D array // call read3DArray() method arr = read3DArray(); // display 3D array // pass to display3DArray() method display3DArray(arr); >// method to return 3D array public static int[][][] read3DArray() < // read input from end-user or // initialize explicitly int[][][] temp = ,>,,>>; // return array return temp; // Or, // directly return annonymous array // return new int[][][] ,>,,>>; > // method to take 3D array and display it public static void display3DArray(int[][][] arr) < System.out.println("3D array,"); for (int[][] i : arr) < for (int[] j : i) < for (int k : j) < System.out.print(k + " "); >System.out.println(); // new line > System.out.println(); // new line > > >

Program for Three Dimensional Array

Java program to create, modify and display the three dimensional array,

public class ThreeDimensionalArray < public static void main(String[] args) < // declare 3d array int[][][] arr = new int[2][3][2]; // initializing the value arr[0][0][0] = 1; arr[0][0][1] = 2; arr[0][1][0] = 3; arr[0][1][1] = 4; arr[0][2][0] = 5; arr[0][2][1] = 6; arr[1][0][0] = 7; arr[1][0][1] = 8; arr[1][1][0] = 9; arr[1][1][1] = 1; arr[1][2][0] = 2; arr[1][2][1] = 3; // displaying 3d Java array System.out.println("Three Dimensional Array is, "); displayThreeDArray(arr); // modifying some values arr[0][0][0] = 9999; arr[0][1][1] = 4656; arr[1][1][1] = 1628; // displaying 3d array after modification System.out.println("\nAfter modifying some values"); System.out.println("Three Dimensional Array is, "); displayThreeDArray(arr); >// method to display 3D array public static void displayThreeDArray(int[][][] a) < for (int[][] i : a) < System.out.println(); System.out.println("Grand parent array holds:" + i); for (int[] j : i) < System.out.println("Parent array holds:" + j); for (int k : j) < System.out.print(" " + k + "\t"); >System.out.println(); > > > >

Three Dimensional Array is,

Читайте также:  Making web page with html

After modifying some values
Three Dimensional Array is,

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Многомерные массивы Java

В Java можно объявить массив массивов, известный как многомерный массив. К примеру:

Здесь мы видим двухмерный массив Java , который может содержать до 12 элементов типа int :

Не забывайте, что индексирование в Java начинается с нуля, поэтому первые элементы массива имеют индекс 0 , а не 1 .

Аналогично можно объявить и трёхмерный ( 3D ) массив. Например:

String[][][] personalInfo = new String[3][4][2];

В примере выше personalInfo — это трёхмерный массив, в котором может быть до 24 (3*4*2) элементов типа String .

В Java составляющие многомерного массива — это тоже массивы. Если вы знаете C/C++ , то может показаться, что многомерные массивы в Java и C/C++ работают одинаково. Но это не совсем так — в Java ряды массивов могут быть разной длины. Разницу мы увидим во время инициализации.

Как инициализировать двумерный массив Java?

Ниже приводится пример инициализации двумерного массива Java :

Каждый компонент массива также представляет собой массив, и длина каждого ряда отличается:

Как инициализировать двумерный массив Java?

Давайте напишем программу, чтобы это доказать:

class MultidimensionalArray < public static void main(String[] args) < int[][] a = < , , , >; System.out.println("Длина ряда 1: " + a[0].length); System.out.println("Длина ряда 2: " + a[1].length); System.out.println("Длина ряда 3: " + a[2].length); > >

При запуске этой программы мы получим:

Длина ряда 1: 3
Длина ряда 2: 4
Длина ряда 3: 1

Поскольку многомерный массив состоит из отдельных массивов (a[0], a[1] and a[2]) , можно использовать метод length для определения длины каждого ряда длины двумерного массива Java.

Пример: вывод на экран всех элементов двумерного массива с помощью циклов :

class MultidimensionalArray < public static void main(String[] args) < int[][] a = < , , , >; for (int i = 0; i < a.length; ++i) < for(int j = 0; j < a[i].length; ++j) < System.out.println(a[i][j]); >> > >

Всегда лучше использовать цикл for…each , когда нужно пройти по элементам массива. Пример сортировки двумерного массива Java можно записать с помощью цикла for…each следующим образом:

class MultidimensionalArray < public static void main(String[] args) < int[][] a = < , , , >; for (int[] innerArray: a) < for(int data: innerArray) < System.out.println(data); >> > >

При запуске этой программы мы получим следующий результат заполнения двумерного массива Java :

Как инициализировать многомерный массив Java?

Многомерный или трёхмерный массив инициализируется почти так же, как двухмерный:

// test — трёхмерный массив int[][][] test = < < , >, < , , > >;

Трёхмерный массив — это массив, состоящий из двумерных массивов. Как и у двумерных массивов Java , его ряды могут быть различной длины.

Пример: программа для вывода элементов трёхмерного массива с помощью циклов :

class ThreeArray < public static void main(String[] args) < // test – трёхмерный массив int[][][] test = < < , >, < , , > >; // цикл for..each проходит по элементам трёхмерного массива for (int[][] array2D: test) < for (int[] array1D: array2D) < for(int item: array1D) < System.out.println(item); >> > > >

При запуске программы вывода двумерного массива Java получаем следующий результат:

1 -2 3 2 3 4 -4 -5 6 9 1 2 3

МК Михаил Кузнецов автор-переводчик статьи «

Источник

Оцените статью