1

I am fairly new to java and I have a problem with following program:

 import java.util.Scanner;

public class Matrix2D { 

private double[][] matrix; 
private int dimX; 
private int dimY;   



public Matrix2D(int row , int col ){  
    Scanner scanner=new Scanner(System.in);
    dimX=col; 
    dimY=row;
    matrix=new double[row][col]; 
    int i ,j;
    for( i=0;i<matrix[row].length;i++) 
    { 
        for( j=0;j<matrix[col].length;j++) 
        {   
            System.out.println("Please enter double at position"+" "+ row +" "+ col);  
            double input=scanner.nextDouble();
            matrix[row][col]=input;  }
    }


}


public static void main(String[] args) {
    Matrix2D test=new Matrix2D(3 ,3 );

}

}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Matrix2D.<init>(Matrix2D.java:17)
    at Matrix2D.main(Matrix2D.java:31)

The program lets me give the first user input , but immediately after it throws the exception above. Any help would be much appreciated.

1 Answer 1

1

You got the indices of your loops mixed up. martix has row rows, with indices 0 to row-1, so matrix[row] is out of bounds.

It should be :

matrix=new double[row][col]; 
for(int i=0;i<row;i++) { 
    for(int j=0;j<col;j++) {   
        System.out.println("Please enter double at position"+" "+ i +" "+ j);  
        double input=scanner.nextDouble();
        matrix[i][j]=input;  
    }
}

or

matrix=new double[row][col]; 
for(int i=0;i<matrix.length;i++) { 
    for(int j=0;j<matrix[i].length;j++) {   
        System.out.println("Please enter double at position"+" "+ i +" "+ j);  
        double input=scanner.nextDouble();
        matrix[i][j]=input;  
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the quick response.You were right , now the program works just fine. Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.