Why can't I create multitable which has 2 rows and 3 collumns, while I can do the one with 3 rows and 2 collumns?
Like in the code below, I cannot display all the slots in the table, as two of them are missing for whatever reason...?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] tab = new int[2][3];
int number = 1;
for (int i = 0; i < tab.length; i ) {
for (int j = 0; j < tab.length; j ) {
tab[i][j] = number ;
}
}
for (int i = 0; i < tab.length; i ) {
for (int j = 0; j < tab.length; j ) {
System.out.printf("tab[%d][%d]=%d \n", i, j, tab[i][j]);
}
}
}
}
CodePudding user response:
tab.length
will give you the length of first dimension. You should use tab[i].length
like below
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] tab = new int[2][3];
int number = 1;
for (int i = 0; i < tab.length; i ) {
for (int j = 0; j < tab[i].length; j ) {
tab[i][j] = number ;
}
}
for (int i = 0; i < tab.length; i ) {
for (int j = 0; j < tab[i].length; j ) {
System.out.printf("tab[%d][%d]=%d \n", i, j, tab[i][j]);
}
}
}
}
CodePudding user response:
In Java, multidimentional arrays don't actually exist. Instead, an int[][]
is just an array with int[]
.
For example, it is perfectly fine to just do this:
tab[1] = new int[7];
Now the array is not a matrix anymore, as the separate arrays each have different sizes. This is called a jagged array. The 'multidimensional' array now looks like this:
0 0 0
0 0 0 0 0 0 0
In your case, tab.length
refers to the length of the outside array. To get the length of each subarray, use tab[i]
instead.
CodePudding user response:
Put the length of column based of specific row e.i tab[row].length in inner loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int row = 3; //setting row here
int col = 4; // setting column here
int[][] tab = new int[row][col];
int number = 1;
for (int i = 0; i < tab.length; i ) {
for (int j = 0; j < tab[i].length; j ) {
tab[i][j] = number ;
}
}
for (int i = 0; i < tab.length; i ) {
for (int j = 0; j < tab[i].length; j ) {
System.out.printf("tab[%d][%d]=%d \n", i, j, tab[i][j]);;
}
}
}