Domanda

Sono un beginner e mi chiedevo se qualcuno potesse dirmi cosa sto facendo di sbagliato qui con questa ricerca di parole? Im bloccato nel verificare ogni riga per una parola specificata nell'argomento formale, attualmente non fa alcun controllo di alcun tipo nel suo metodo booleano di base che restituisce vero se una parola viene trovata all'interno di una riga dell'array. Assumendo l'array di ricerca di parole è rettangolare

    public boolean checkRow( char[][] puzzle, String w)
{
    int counter = 0;
    boolean match = true;
    for ( int row = 0; row < puzzle.length; row++)
    {
        counter = 0;


        for ( int col = 0; col < puzzle[row].length; col++)
        {
            if ( counter <= w.length() )
            {
                char word = puzzle[row][col];


                if( w.charAt(counter) == word)
                {
                    match = true;
                    counter++;
                }
            }


            else if ((counter == w.length()) && (match == true))
            {
                return true;
            }


             else 
            {

                match = false;
                counter = 0;
            }



        }
    }


    return match;
}
È stato utile?

Soluzione

Ecco il tuo codice corretto

public boolean checkRow(char[][] puzzle, String w) {
    int counter = 0;
    boolean match = true;
    for (int row = 0; row < puzzle.length; row++) {
        counter = 0;
        match = false;

        for (int col = 0; col < puzzle[row].length; col++) {
            if (counter < w.length()) {
                char word = puzzle[row][col];

                if (w.charAt(counter) == word) {
                    match = true;
                    counter++;
                } else {
                    match = false;
                    counter = 0;
                }

                if ((counter == w.length()) && (match == true)) {
                    return true;
                } 
            }
        }
    }
    return false;
}

Ma questo non è il modo migliore per fare il tuo assegno, ecco molto più fluido e ancora più veloce (circa 5 volte, lo testerei)

public boolean checkRow2(char[][] puzzle, String w) {
    String rowStr = null;
    for(int row = 0; row < puzzle.length; row++) {
        rowStr = new String(puzzle[row]);
        if(rowStr.contains(w)) return true;
    }
    return false;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top