Nicholas Ray - 9 months ago 30

Java Question

I have a 2 dimensional String array and I am trying to find if the rows have common elements between them and what that element is. It should look at the element that is in (0,0) and compare it to the element that is in (1,0), (1,1), (1,2) and so on. I am trying to use nested for loops but I can't seem to get it right. Could someone tell me what is wrong with my code and how I should fix it?

`for(int i = 0; i < times.length; i++ ){`

for(int j = 0; j < times[i].length; j++ ){

if(i+1 < times.length)

if(times[i][j].equals(times[i+1][j])){

System.out.println(times[i][j + " = " + times[i+1][j])

}

}

}

Answer

I will try to keep this as intuitive and easy to understand as possible. The bounds for the first row is [0, times.length - 2]. That way, the bounds for the second row will be [1, times.length - 1]. For each element in first row, I will check every element in the second row. The following code demonstrates that.

```
for(int row = 0 ; row < times.length - 1 ; row++) {
for(int colFirst = 0 ; colFirst < times(row).length ; colFirst++) {
for(int colSecond = 0 ; colSecond < times(row + 1).length ; colSecond++) {
if(times[row][colFirst].equals(times[row+1][colSecond]))
System.out.println(times[i][j + " = " + times[i+1][j]);
}
}
}
```