0

I'm trying to do a program which uses a matrix and makes a new one with each element being the sum of every adjacent element of the original one plus itself.

It's very easy to understand that the "edge" values of the matrix, if you access them by the matrix indexes, then you may be getting something like matrix[-1][0]. The thing is, Java throws an exception so the program crashes.

Is it possible to catch it and get the value it has anyway? Even if it's not initialized, because the thing is that mathematically you can multiply by 0 the whole term when it's accessing an out of bound address.

public class OpMatriz {

    public static void main(String[] args) {
        
        int[][] miMatriz= {{1,9,10,7,2,1,9},{-5,1,9,10,7,2,1},{2,1,3,1,5,2,11}};
        imprimeMatriz(miMatriz);
        
        miMatriz = OpMatriz.sumaAdyacentes(miMatriz);
        
        imprimeMatriz(miMatriz);
        

    }
    
    public static int[][] sumaAdyacentes(int[][] matriz){
        
        int n = matriz.length;
        int m = matriz[0].length;
        
        int[][] matrizAux = new int[n+2][m+2];
        int[][] matrizRes = new int[n][m];
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                matrizAux[i+1][j+1] = matriz[i][j];
            }
        }
        
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                matrizRes[i-1][j-1] = matrizAux[i-1][j] + matrizAux[i][j+1] + matrizAux[i+1][j] + matrizAux[i][j-1] + matrizAux[i][j];
            }
        }
        
        return matrizRes;
    }
    
    public static void imprimeMatriz(int[][] matriz) {
        for (int i = 0; i < matriz.length; i++) {
            System.out.print("| ");
            for (int j = 0; j < matriz[0].length; j++) {
                System.out.printf("%2d ", matriz[i][j]);
            }
            System.out.println("|");
        }
        System.out.println();
    }
    

}

My current program just makes a "intermediate" matrix a bit bigger than the original, all initialized in 0, so it can add it for the edge cases. Now, I don't want to use any conditional, as it's the idea of the exercise to improve the algorithm.

matrizRes[i][j] = i * matriz[i-1][j] + (m+1-j) * matriz[i][j+1] + (n+1-i) * matriz[i+1][j] + j *matriz[i][j-1] + matriz[i][j];

My idea is using an equation like this, so when a term is trying to use an invalid index, whatever value it has, it's going to get multiplied by 0. So doing this, i can just not use this "intermediate" matrix and work it out with just the original.

So, finally again, is there a way to get the value of an ArrayIndexOutOfBoundsException even if it's not initialized?

PD: Sorry for Spanish programming, it's for a university assignment.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 4
    "because the thing is that mathematically you can multiply by 0 the whole term when it's accessing an out of bound address" I don't see anything "mathematical" about accessing an invalid index? What "0" are you talking about? An invalid index does not contain 0 - It's undefined. You should just write the algorithm in a way that you ***never*** access an invalid index. – Sweeper Aug 25 '22 at 01:41
  • 1
    Why don't you want to use any conditional? How exactly does having no conditionals "improve the algorithm"? – Sweeper Aug 25 '22 at 01:43
  • 1
    *when a term is trying to use an invalid index, whatever value it has...* Invalid indexes don't any value because they don't exist. You can't multiply their value same as you can't multiply an undeclared variable. – shmosel Aug 25 '22 at 01:43
  • 3
    write an accessor method `get(matrix, row, col)` that checks the row and col values and returns 0 for out-of-bounds references. but **why**? – access violation Aug 25 '22 at 01:47
  • 1
    You don't explain what you mean by "improve the algorithm", but note that throwing an exception is very expensive relative to checking a couple of index values. – tgdavies Aug 25 '22 at 03:19
  • 1
    I don't see how you can possibly get `ArrayIndexOutOfBoundsException` with this code. Your indices are all confined to `0..array,length-1`, which is correct. All you can get is uninitialized *elements,* which will be zero. Unclear what you're asking. – user207421 Aug 25 '22 at 04:09

1 Answers1

1

Looks like you want to know the bounds or more information on Exceptions.

But we must not catch the exception and perform logic around it. It is not recommended.

But if you still want to know the information about the exception. The exception message is quite descriptive. You can use e.getMessage() Here is an example of e.getMessage().

Index 3 out of bounds for length 3

To find the bounds we can parse the error message. Here is an example.

    int[][] matrix = new int[3][];
    try {
      int assign[] = matrix[3];
    } catch (IndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
      Stream<MatchResult> matchResultStream = Pattern.compile("\\d+").matcher(e.getMessage()).results();
      List<String> matchResults = matchResultStream.map(x -> x.group()).collect(Collectors.toList());
      if (matchResults.size() > 1) {
        System.out.println("Error Index " + matchResults.get(0));
        System.out.println("Max Index Bounds " + matchResults.get(1));
      }
    }

Output:

    Index 3 out of bounds for length 3
    Error Index 3
    Max Index Bounds 3

anantha ramu
  • 171
  • 4