Spaceman
Spaceman

Reputation: 11

For loop only working first time

I'm trying to make a program to find a words in a words search in Java. I know it's been done before, but I'm still learning, and it will be cooler if I made it myself. Anyway, I've found that my main for loop for scanning the grid only executes for the first word I want to find. Here's the part of my code that finds the word:

while (!word.equalsIgnoreCase("/exit")) {
    { //Find word
        Pair cursor = new Pair();
        Pair direction = new Pair();
        Pair location = new Pair();

        for (int x = 0; !whole_word_found && x<grid.length; x++) {  int y = 0;
            for (y = 0; !whole_word_found && y<grid[x].length; y++) {
                cursor = new Pair(x,y);
                //Lots of word-finding code, including writing whole_word_found and using the three pairs listed above
            }
        }

        //Print location of word
        if (word.length() != 1) {
            if (whole_word_found) {
                System.out.printf("The word is located at %s going %s.%n",location.toString(0),direction.toString(0));
            } else {
                System.out.println("Sorry, word not found.");
            }
        }
    } //Find word

    //Get next word
    System.out.println("Enter another word, or type \"/exit\" to exit.");
    input = new Scanner(System.in);
    word = input.nextLine().replaceAll(" ","");
}

All variables are properly initialized, and Pair is a classes I whipped up to hold the value of an ordered pair (x,y). I just didn't like having two separate values for every x-y pair I had to make (though I technically still do).

Anyway thanks for the help if you can find it.

Upvotes: 0

Views: 192

Answers (1)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

You need to reset whole_word_found at every iteration of the loop.

while (!word.equalsIgnoreCase("/exit")) {
    // ...
    whole_word_found = false;
    for (int x = 0; !whole_word_found && x<grid.length; x++) {
    // ...

Upvotes: 1

Related Questions