menna menna - 7 days ago 7
Java Question

Java looping two-dimensional array with if conditions

I'm trying to do a certain project and there is this part in which I want to loop in a two-dimensional (2D) array and if the certain value of

i
and
j
then do something.

To be more specific my 2D array is defined for files and users (the attached photo might explain well); I want, for example, when
i = 0
and
j = 0
equals
1
then print out that user
1
can write in file. I was able to iterate over the array and find the indexes where
1
's occur in the array with the following code:

my 2d array defined

public class Test {
public int counteri = 0;
public int counterj = 0;

public void readpermission(int[][] array) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 6; j++) {
if (array[i][j] == 1) {
counterj = j;
counteri = i;
System.out.println("found 1's at index =" + counteri + " " + counterj);
}
}
}
}
}

found 1's at index =0 0,

found 1's at index =0 1

found 1's at index =0 4

found 1's at index =1 1

found 1's at index =1 2

found 1's at index =1 3

found 1's at index =1 4

found 1's at index =1 5


When the first value is
0 0
, I want an output that user
1
can write in file
1
and when the output is
0 1
I want an output stating that user
1
can read in file 1...and so on.

Answer

Given your last comment:

if(array[i=0][j=0]==1) 

could be

if (i==0 && j==0 && array[i][j] == 1)

But the point is: that is really basic java syntax; and you should not need to come here and ask about that. Instead: you study tutorials and education materials that tells you how to do work with java syntax, for example here.

But please note: the whole thing that you are describing doesn't make too much sense. You are using int values to model permissions. That is not a good idea. Instead: you could create your own Permission class; or at least: use an enum instead of int values. Assuming that an int with value 1 ... means "write access" is simply a very naive and actually not-at-all intuitive model.