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?
It takes one less input because of:
if(i == 0 && j==0)
return;
Element [0,0] should be set as well. Try to change the condition to be like:
if (i == -1 || j == -1)
return;
Index out of bounds because you should start with [length - 1] index:
initialize(matrix, number - 1, number - 1);
You can also add message before entering of each element so user knows which element he is entering. And also print the matrix in the end to make sure it is correct.
Final code as below:
import java.util.Arrays;
import java.util.Scanner;
public class DSPro {
static Scanner scan = new Scanner(System.in);
static double[][] matrix;
public static void main(String[] args) {
System.out.println("What would be the number of n?");
int number = Integer.parseInt(scan.nextLine());
matrix = new double[number][number];
initialize(matrix, number - 1, number - 1);
for (double[] row : matrix) {
System.out.println(Arrays.toString(row));
}
}
public static void initialize(double[][] matrix, int i, int j) {
if (i == -1 || j == -1) return;
System.out.println("Enter element [" + i + ", " + j + "]");
matrix[i][j] = Double.parseDouble(scan.nextLine());
if (j == 0) initialize(matrix, i - 1, matrix.length - 1);
else initialize(matrix, i, j - 1);
}
}