试图在单个二维数组中的行之间找到公共元素 [英] Trying to find common elements between the rows in a single 2D array

查看:46
本文介绍了试图在单个二维数组中的行之间找到公共元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维字符串数组,我试图找出行之间是否有公共元素以及该元素是什么.它应该查看位于 (0,0) 中的元素并将其与位于 (1,0)、(1,1)、(1,2) 等中的元素进行比较.我正在尝试使用嵌套的 for 循环,但似乎无法正确使用.有人能告诉我我的代码有什么问题以及我应该如何修复它吗?

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])
                }
        }
    }

推荐答案

我会尽量让这一切尽可能直观和易于理解.第一行的边界是 [0, times.length - 2].这样,第二行的边界将是 [1, times.length - 1].对于第一行中的每个元素,我将检查第二行中的每个元素.下面的代码演示了这一点.

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]);
        }
    }
}

这篇关于试图在单个二维数组中的行之间找到公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆