-3

I am trying to make the following code or something similar to work:

static String[][] arr = new String[4][4];
static int[][] arr2 = new int[4][4];



for(int i = 0; i < arr.length; i++){
        for (int j = 0; j < arr[0].length; j++) {
            arr[i][j] = "1";
            arr2[i][j] = Integer.parseInt(arr[i][j]);
            if(arr2[i][j] instanceof int){
                System.out.println("Works");
            }
        }
    }

Instead the IDE marks it red and gives an error "Inconvertible types; cannot cast int to int".

Can somebody help?

Uio443
  • 3
  • 2
  • int[] is not int –  Nov 23 '17 at 02:10
  • The array is declared as 2d int array, so any index that you'll check is of type int, further `instanceof` doesn't work with primitive types. See: https://stackoverflow.com/questions/12361492/how-to-determine-the-primitive-type-of-a-primitive-variable what do you *really* want to check? – Nir Alfasi Nov 23 '17 at 02:12
  • can `instanceof` even be used for plain old value types like char,int,boolean? – selbie Nov 23 '17 at 02:12
  • 1
    Impossible to answer without knowing how is `arr2` actually declared and what you expect to do with your check. `instanceof` operator doesn't work with primitives in first place, in addition array type rules doesn't allow casting between array types so what you think to do probably won't work. – Jack Nov 23 '17 at 02:12
  • 2
    Smells like an [XY Problem](http://xyproblem.info/) type question. Please show real code and make your question much more concrete so that it can be well answered. – Hovercraft Full Of Eels Nov 23 '17 at 02:12
  • @jack "can't cast int to int" answers your question – Nir Alfasi Nov 23 '17 at 02:12
  • 4
    You can't use `instanceof` with primitive types. It wouldn't make any sense to. – shmosel Nov 23 '17 at 02:13
  • @alfasin: no, that would rise an error at `arr2[i][j]` since subscript `[]` operator is not allowed on an `int`. Actually it would be "array required but found `int`". – Jack Nov 23 '17 at 02:16

1 Answers1

-1

With the limited information you provided. You will have to change every place where it says int to Integer because instanceof cannot check for primitive types. Your code would look like this:

static String[][] arr = new String[4][4];
static Integer[][] arr2 = new Integer[4][4];


for(int i = 0; i < arr.length; i++){
        for (int j = 0; j < arr[0].length; j++) {
            arr[i][j] = "1";
            arr2[i][j] = Integer.parseInt(arr[i][j]);
            if(arr2[i][j] instanceof Integer){
                System.out.println("Works");
            }
        }
    }
StackDoubleFlow
  • 323
  • 4
  • 12