+ 4
How to print multidimentional arrays without knowing it's size in java?
I came to know this code to print multi-array without knowing size, it's working but i still cannot understand it tbh. If anyone may help me in understanding this or may be teach a better way to do it, please! Code: public class Program { public static void main(String[] args) { int[ ][ ] myArr = { {1, 2, 3}, {4}, {5, 6, 7} }; for(int x=0; x<myArr.length; x++){ for(int y=0; y<myArr[x].length; y++) System.out.print(myArr[x][y] +" "); System.out.println(); } } }
4 odpowiedzi
+ 13
Let me try
the outer for loop goes through all the elements in the array(which are arrays themselves).
Considering when x = 0
myArr[0] = {1, 2, 3}
myArr[0].length = 3(since myArr[0] has 3 elements)
the inner for loop can then iterate over myArr[0]'s elements
the first element in myArr[0] is 1 and it can be accessed by using : myArr[0][0](the first element of the first array)
I don't know if this was helpful but I hope it was
+ 19
//by using enhanced for loop
//i just saw that for 2d array ☺
https://www.sololearn.com/Discuss/1012222/?ref=app
+ 6
Understood! Thank You! 🤝
+ 4
There’s also an Arrays class in util package that allows you to do lots of things with arrays. So that given you import this class:
import java.util.Arrays;
you can do this:
System.out.println(Arrays.deepToString(myArr));
and you don’t even have to know how many dimensions your array has...