how do I create a 2d array, where the user choos the size of the array? or have to make this:
1 2 3 4 5
1 O O O O O
2 O O O O O
3 O O O O O
4 O O O O O
5 O O O O O

7 Years
Discussion Span
Last Post by Dhruv Gairola

how do I create a 2d array, where the user choos the size of the array?

You ask user for input(command line write message and ask for entry, GUI provide a field to be fill in), you read the input(command line use Scanner class or similar, GUI use provided getText() or getString() method), you validate the input (write method to validate input to see that it is valid number) and if correct you use it.


You question is unclear, and you have not put in sufficient effort. To get you started look at creating the array with a defined size.

Object[][] array = new Object[3][5];

The above code will create a 3(rows) x 5(columns) grid that can hold objects. You should be able to expand on that creating a grid using a value entered by a user (as mentioned above by Peter).

Edited by cale.macdonald: n/a


accept user input using Scanner and System.in or perhaps a GUI, then use that number to initialise a 2D array (im assuming u need a n by n array).
e.g. int [] [] arr = new int [n] [n];

Votes + Comments
Just repeating that was already said...
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.