I should write a java program that contains giving values to a matrix and printing the values of a matrix recursively. I tried this code,but everytime I give the input it gives index out of border exception.If I pass one less than the number variable,it takes one less input and
import java.util.Scanner;
public class DSPro {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
static double matrix1[][];
static double matrix2[][];
static double result[][];
System.out.println("What would be the number of n?");
int number = Integer.parseInt(scan.nextLine());
matrix1 = new double [number][number];
matrix2 = new double [number][number];
result = new double [number][number];
initialize(matrix1, number, number);
}
public static void initialize(double [][] matrix,int i,int j)
{
if(i == -1&&j==-1)
return ;
matrix[i][j] = Double.parseDouble(scan.nextLine());
if(j == -1)
initialize(matrix,i-1,matrix[0].length);
else
initialize(matrix, i, j-1);
}
}
I also tried adding 1 to number and passing the function number-1 instead of n and the exception changed into this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at data_structure.DSPro.initialize(DSPro.java:168)
at data_structure.DSPro.initialize(DSPro.java:171)
at data_structure.DSPro.initialize(DSPro.java:174)
at data_structure.DSPro.initialize(DSPro.java:174)
at data_structure.DSPro.main(DSPro.java:53)
Do you think my recursive code is the problem or the way I'm passing it to the method?