Chandra Kishore Chandra Kishore - 2 months ago 11
Java Question

Get Array length from one class to another class

i need help in getting the array length from another class. i.e., passing the length of array from one class to another. Here is the problem.

Testmatrix.java

public class TestMatrix{
int rows;
int cols;
double data[][] = new double[4][4];

public Matrix() {
super();

rows=1; cols=1;
for(int i=0; i<=rows;i++)
{
for(int j=0; j<=cols;j++)
{
data[i][j] = 0.0;
}
}
}

public void print(){

for (int i = 0; i < data.length ; i++) {
for (int j = 0; j < data.length ; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
}


Here is the main class
Main.java

public class Main {

public static void main(String[] args){
TestMatrix m1 = new testMatrix();
m1.print();
}
}


Everything seems right in the constructor. But the problem is the print function. The size of the data should be 2. But its is taking the value of 4 declared that is initialised. Someone solve this for me. I need to get to print 2x2 matrix( with all 0's) but i'm getting 4x4 matrix( with all 0's)

Thanks in advance **

Answer

Initializing array doesn't change the size of an array. If you want to print acording to new row and column size, change your print() method to:

public void print() {    
    for (int i = 0; i <= rows ; i++) {
        for (int j = 0; j <= cols ; j++) {
             System.out.print(data[i][j]);          
        } 
        System.out.println();
     }
}

Note: Another important thing, you don't need to initialize the double array to 0.0. This array is by default initialized to 0.0 as this is an instance field of the class. According to Oracle:

Each class variable, instance variable, or array component is initialized with a default value when it is created.

For type double, the default value is positive zero, that is, 0.0d.

Comments