int[][] input = new int[3][];
int count = 1;
for(int i = 0; i <= 2 ; i++ ) {
for(int j = 0; j <= 2; j++) {
input[i][j] = count++;
}
}
Fifth line throws an error.
int[][] input = new int[3][];
int count = 1;
for(int i = 0; i <= 2 ; i++ ) {
for(int j = 0; j <= 2; j++) {
input[i][j] = count++;
}
}
Fifth line throws an error.
Second dimension of the array is empty.
int[][] input = new int[3][];
Try this:
int[][] input = new int[3][3];
You need to initialize the second dimension
1) int[][] input = new int[3][3];
or
2)
for(int i = 0; i <= 2 ; i++ ){
input[i] = new int[3];
}
Because you second array dimension is not specified.
This should run:
int[][] input = new int[3][3];
int count = 1;
for(int i = 0; i <= 2 ; i++ ){
for(int j = 0; j <= 2; j++){
input[i][j] = count++;
}
}
See executable example
int[][] input = new int[3][];
this type of array are called ragged array. in you have to define the size of column for each row. like this:
input[0]=new int[2];//for row 1 (row 1 contain 2 column)
input[1]=new int[5];//for row 2 (row 2 contain 5 column)
input[2]=new int[1];// for row 3 (row 3 contain 1 column)
so define column size for each row as you wish
/*Ragged Arrays are multidimensional arrays in which the rows have different no of cols. */
class Ragged
{
public static void main(String args[])
{
//declaration of a ragged array
int arr[][] = new int[3][];
//declaration of cols per row
arr[0] = new int[4];
arr[1] = new int[2];
arr[2] = new int[3];
int i, j;
for(i =0; i< arr.length; i++)
{
for(j =0 ; j< arr[i].length; j++)
{
arr[i][j] = i + j+ 10;
}
}
for(i =0; i< arr.length; i++)
{
System.out.println();//skip a line
for(j =0 ; j< arr[i].length; j++)
{
System.out.print(arr[i][j] + " ");
}
}
//-------------more----------------
int temp[];//int array reference
//swap row2 and row3 of arr
temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;
System.out.println();//skip a line
for(i =0; i< arr.length; i++)
{
System.out.println();//skip a line
for(j =0 ; j< arr[i].length; j++)
{
System.out.print(arr[i][j] + " ");
}
}
}//main
}//class
/* TO declare a ragged array define a multi dimensional array with the val of last dimension missing.
The explicitly define the size of the last dimension for all the rows. */
You need specify size for second array during initialization. Also you can use .length property of array to avoid hard coded sizes.
int[][] input = new int[3][3];
int count = 1;
for(int i = 0; i <= input.length ; i++) {
for(int j = 0; j <= input[i].length; j++) {
input[i][j] = count++;
}
}