-1

Returns the entry of this matrix located at the given one-based row and column indexes. Throws an exception if row or col is not 1 or 2.

public double get(int row, int col){
   if (row != 1 || row != 2){
      throw IndexOutOfBoundsException("Row not valid");
   }

   if (col != 1 || col != 2){
      throw IndexOutOfBoundException("Column not valid");
   }

   return data[row - 1][col - 1];
}

This is the code for my method, but even if I call the method with the parameters row = 1, and col = 2; it shows an IndexOutOfBoundsException. Any ideas on how to fix this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ell10t
  • 7
  • 1
  • 3
    `if (row != 1 || row != 2)` will always be true, because row cannot be equal to 2 values at the same time. If row is `1` then `row != 2` will be true and if row is `2` then `row != 1` will be true and you used an or `||` between those 2 conditions. You need to use an and condition `&&` to check that row is not unequal to 1 **and** not unequal to 2. – OH GOD SPIDERS Mar 07 '22 at 15:37
  • You want `row != 1 && row != 2`. Currently, this check will always be true. – f1sh Mar 07 '22 at 15:37

1 Answers1

2

Assuming the matrix data is large enough, try using && (and) rather than || (or):

public double get(int row, int col) {
   if (row != 1 && row != 2) {
      throw new IndexOutOfBoundsException("Row not valid");
   }
   if (col != 1 && col != 2) {
      throw new IndexOutOfBoundException("Column not valid");
   }
   return data[row - 1][col - 1];
}

Instead of chaining a bunch of conditions and you could also perhaps consider defining a Set each for the valid columns and rows that are allowed:

private static final Set<Integer> VALID_ROWS_TO_GET = Set.of(1, 2);
private static final Set<Integer> VALID_COLS_TO_GET = Set.of(1, 2);

...

public double get(int row, int col) {
    if (!VALID_ROWS_TO_GET.contains(row)) {
        throw new IndexOutOfBoundsException("Row not valid");
    }
    if (!VALID_COLS_TO_GET.contains(col)) {
        throw new IndexOutOfBoundsException("Column not valid");
    }
    return data[row - 1][col - 1];
}
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40