How to print the last value of 2d array

Assuming you don't know the size of the arrays, is there a way to use .length or .size to get the final value of the 2d array? If no loop allowed either. I was just a little curious.

A 2d array in Java (and many other languages) is just an array of 1d arrays. If you think of it as rows and columns, then each row may have the same number of columns, but that's not necessarily true. You get the number of rows by a.length and the number of columns in the second row, for example, as a[1].length. That should be enough for you to finish your assignment.

Yes, the original thing I got stuck in my mind was that I forgot each row has same number of columns. a[1].length == a[2].length so this will work

System.out.println(array[array.length-1][array[0].length-1]);

As picking any row will yield same amount of columns for traditional array. But you also mentioned that each row may have different columns. While I am not quite familiar with that but I think I have heard of it before. I am not sure how to initialize array like that. But I came up with the following code, it might be able to still generate the last value of the 2d array when each row may have different numbers of columns and also if the numbers of columns was not given. I guess this is what I was looking for when I first asked the question.

System.out.println(array[array.length-1][array[array.length-1].length-1]);

System.out.println(array[array.length-1][array[0].length-1]);

As picking any row will yield same amount of columns for traditional array. But you also mentioned that each row may have different columns. While I am not quite familiar with that but I think I have heard of it before. I am not sure how to initialize array like that. But I came up with the following code, it might be able to still generate the last value of the 2d array when each row may have different numbers of columns and also if the numbers of columns was not given. I guess this is what I was looking for when I first asked the question.

System.out.println(array[array.length-1][array[array.length-1].length-1]);

Yep, that looks right to me. Good work!

You've gotta fight it! Don't give in! Read this tiny ad:

Thread Boost - a very different sort of advertising

https://coderanch.com/t/674455/Thread-Boost-feature
This thread has been viewed 1352 times.

All times above are in ranch (not your local) time.

The current ranch time is

Apr 24, 2018 16:57:46.

The current ranch time is

Apr 24, 2018 16:57:46.