I wanna create a ragged array (two-dimensional array) that the user inserts the values one at a time. I would usually create them like so:
int[][] array = {{1,2,3}, {6,7}}
but I don't know their size beforehand.
How can I create an array like that?
Asked
Active
Viewed 1,211 times
-3
2 Answers
0
You should initialize a jagged/ragged (same thing) array like this: int array[][] = new int[4][];
Then you can (for example):
array[0] = new int[5];
array[1] = new int[5];
array[2] = new int[5];
array[3] = new int[5];
Then you can:
for (int i = 0; i < 4; i++){
for (int j = 0; j < i + 1; j++) {
array[i][j] = i + j;
}
}
And if you want to print:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < i + 1; j++)
System.out.print(array[i][j] + " ");
System.out.println();
}
You'll get the output:
0
1 2
2 3 4
3 4 5 6
Of course that if you want to get the input from the user you can substitute any assignment here with Scanner.nextInt();
.
Edit after comment: You must specify the size, if you don't wish to do that, then use:
ArrayList<ArrayList<Integer>> array = new ArrayList<ArrayList<Integer>>();

Idos
- 15,053
- 14
- 60
- 75
-
ı don't know the length of the array. new int[4][];in this code ı dont know the row size and column size – John Doe Dec 13 '15 at 14:01
0
Proper usage of the scanner would be
Scanner input = new Scanner(System.in);
int variable = input.nextInt();
Your IDE should include the java package on its own for you to use Scanners.
in relation to @Idos, with an ArrayList, you will be using
array.add(variable);
rather than just selecting an index of the array. I am sure there are plenty of tutorials on how to use ArrayLists that you can find more info about them.

Bill Kleinhomer
- 58
- 1
- 8