简体   繁体   English

Java wordsearch方法,搜索给定的二维数组

[英]Java wordsearch method, searching given 2d array

I am trying to pass a word to my findWord method which checks a 2d array of stype String[][] "a" for said word. 我正在尝试将一个单词传递给我的findWord方法,该方法检查表示该单词的stype String [] []“ a”的二维数组。 Row and column are the dimensions of "a". 行和列是“ a”的尺寸。 I am not checking diagonal or reverse, only forwards. 我不是在检查对角线或反向,而只是向前。 I believe that nearly if not all of my logic is correct, but I think I'm getting a bounds error. 我相信,即使不是全部,我的逻辑几乎都是正确的,但是我认为我遇到了界线错误。 No error is being thrown, but the code just isn't working properly by returning false in random cases that it should return true. 没有引发任何错误,但是代码在随机情况下应返回true,因此返回false只是无法正常工作。 Code compiles and runs fine. 代码编译并运行良好。 (ie it checking past the amount of columns that exist) . (即检查过去的列数)

public boolean findWord(String word)  {
    int cL = column;
    for(int i = 0; i < row; i++) {
        for(int j = 0; j < column; j++) {
            if(a[i][j].equals(word.substring(0,1))) {
                int c = 1;
                int parameter = j + word.length();
                if(parameter <= cL) {
                    for(int k = j; k < parameter; k++) {
                        if(!a[i][k].equals(word.substring(c,c+1)))
                            return false;
                        c++;
                    }
                    return true;
                }
            } else {
                return false;
            }
        }
    }
    return true;
}

I have run a few test cases. 我已经运行了一些测试用例。 I have not yet found a case where your method returns true despite the word being in the array. 我还没有发现尽管单词在数组中但您的方法仍返回true的情况。

The flaws I have seen in your code are: 我在您的代码中看到的缺陷是:

You start looking in a[0][0] . 您开始寻找a[0][0] If the string found here isn't equal to the first letter of your word, you immediately return false without looking any further. 如果在此找到的字符串不等于单词的第一个字母,则无需进一步查找即可立即返回false

Say that the first letter of the word does match a[0][0] . 假设单词的第一个字母与a[0][0]匹配。 Now you set c to 1, but since i and k are 0, you now compare the second letter of the word to a[0][0] . 现在将c设置为1,但是由于ik为0,因此现在将单词的第二个字母与a[0][0] That is unlikely to match. 那不太可能匹配。 It only does of the word begins with the same letter twice. 它只对单词以相同字母开头的单词进行两次。

Finally, I did manage to get a StringIndexOutOfBoundsException , namely by searching for aa in a row containing a , b , c . 最后,我确实设法获得了StringIndexOutOfBoundsException ,即通过在包含abc的行中搜索aa Second time through the innermost loop c is 2, and you therefore try to take out the substring between indices 2 and 3 of a word that has length 2. 第二次通过最里面的循环c是2,因此您尝试取出长度为2的单词的索引2和3之间的子字符串。

You've got some fixing to do. 您需要进行一些修复。 Enjoy your work. 好好工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM