有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用字符检查2d数组中的某些单词(家庭作业)

我目前正在编写一个程序,要求我接受与下面类似的输入。 6 6 d e v o l g r e d p h k qchzjc p o a f o v a m n l qtfoxb 前两个整数表示行和列,其余的表示要放置在方法中的实际字符。我已经成功地创建了一个在数组中创建和读取的方法。 该程序是一个单词搜索解谜程序。它需要几种方法,但我需要关注的是“检查”方法和左右检查。。。到目前为止,这是我为这个方法编写的代码

public static boolean checkUp(char [][] puzzle, String word, int row, int col) {
        System.out.println("Row: " + row +  " Col: " + col + " Word: " + word.charAt(0) + " CurLet: " + puzzle[row][col] + " Word length: " + word.length());
        if (row==0) {
            return false;
        } else if (word.length()==1) {
            return true;
        } else if (word.charAt(0) == puzzle[row][col]){
            checkUp(puzzle,word.substring(1),row-1,col);            
        }
        return false;
    }

有些限制,我必须逐字符读取数组和数组中的所有内容,我无法将其转换为字符串。如果它们匹配,在这个特定的示例中,我只需将行计数向下移动1即可上移。 有没有人有更好的办法来解决这个问题?在这一点上我完全被难住了,事实上我迷路了。我的朋友帮我写了这篇文章,但我真的不知道他到底想做什么


共 (1) 个答案

  1. # 1 楼答案

    首先,您必须检查单词是否比给定的行或列长。然后您迭代单词并比较字符

    public static boolean checkUp(char[][] puzzle, String word, int row, int col) {
        if (row + 1 - word.length() < 0) return false;
    
        for (int i = row; i > row - word.length(); i ) {
            if (puzzle[i][col] != word.charAt(i)) {
                return false;
            }
        }
        return true;
    }
    
    public static boolean checkRight(char[][] puzzle, String word, int row, int col) {
        if (col + word.length() > puzzle[row].length) return false;
    
        for (int i = col; i < col + word.length(); i++) {
            if (puzzle[row][i] != word.charAt(i)) {
                return false;
            }
        }
        return true;
    }