-2

So i wrote a simple code

int k=3;
if (k==3)
{ int a[i][j]=new int[10][10];  }
a[2][3]= 4;
System.out.println(a[2][3]);

I am getting an error in atom editor that cannot find symbol , I want my array to be initialized in if statement

Coder
  • 43
  • 1
  • 8
  • where is `atom` define ? – Ravi Sep 20 '17 at 03:28
  • Atom editor i am using – Coder Sep 20 '17 at 03:30
  • What if `k != 3`? – shmosel Sep 20 '17 at 03:31
  • Actually i am using a code in which if my certain variable (Lets say k) is equal to 1 then i want to declare (a[]) as a 1d array and if k=3 then declare (a[][]) as a 2 d array. So after the initialization of array is done , later in my code i want to use the array a . Hence it is mandatory for me to declare a in if statement depending on the value of k – Coder Sep 20 '17 at 03:35
  • How are you planning on using the array if you don't know its dimensions? – shmosel Sep 20 '17 at 03:40
  • I have variables which are entered by user to make my dimensions, but the 2-d or 3-d will depend on the value of k – Coder Sep 20 '17 at 03:48

1 Answers1

1
int a[][]=new int[10][10]; // the bounds are taken care by the new declaration

I want my array to be initialized in if statement

Also if you put it under if, that would be local to the if. Hence what would work for you is:

if (k==3) { 
    int a[][]=new int[10][10]; 
    a[2][3]= 4;
    System.out.println(a[2][3]);
}

A better practice to declare an array that can be used not just locally would be somewhat like -

int a[][]=new int[10][10]; 
if (k==3) { 
    a[2][3]= 4;
}
System.out.println(a[2][3]);
Naman
  • 27,789
  • 26
  • 218
  • 353
  • Actually i am using a code in which if my certain variable (Lets say k) is equal to 1 then i want to declare (a[]) as a 1d array and if k=3 then declare (a[][]) as a 2 d array. So after the initialization of array is done , later in my code i want to use the array a . Hence it is mandatory for me to declare a in if statement depending on the value of k – Coder Sep 20 '17 at 03:35
  • @Coder Well I am sure there is a dupe for that type of creation in SO, just couldn't find one at this point of time. You might though want to rethink your design of creating multi dimensional arrays based on a certain input. – Naman Sep 20 '17 at 03:37