Unit 5: Lesson 7: #2 (accelerated help)

I have a student who wants to pass the phrases as a 1D array. We (he) are having trouble doing this, any suggestions???

Hi Jeff,

When I click the link you gave it just takes me to Code.org’s landing page and not to a Java Lab project. However, I reworked U5L7 Level 2’s PhraseFinder class to just use a 1D array:

/*
 * Analyzes phrases and sentences
 */
public class PhraseFinder {

  public static String countPhrases(String[] sentences, String targetPhrase) {
    String result = "";
    
    for (int index = 0; index < sentences.length; index++) {
      int phraseCount = 0;
      
      
        String currentPhrase = sentences[index];
        int location = currentPhrase.indexOf(targetPhrase);

        if (location != -1) {
          phraseCount++;
        }
      

      result += "Index #" + index + ": " + phraseCount + " times\n";
    }

    return result;
  }

  public static String findLongestString(String[][] sentences, String targetPhrase) {
    int longestLength = 0;
    int longestRow = -1;
    int longestCol = -1;
    
    for (int row = 0; row < sentences.length; row++) {
      for (int col = 0; col < sentences[row].length; col++) {
        String currentPhrase = sentences[row][col];
        int location = currentPhrase.indexOf(targetPhrase);

        if (location != -1 && currentPhrase.length() > longestLength) {
          longestLength = currentPhrase.length();
          longestRow = row;
          longestCol = col;
        }
      }
    }

    if (longestRow == -1 && longestCol == -1) {
      return "No string containing the target phrase was found.";
    } else {
      return "The longest string containing the target phrase is \"" + sentences[longestRow][longestCol] +
             "\" at row #" + longestRow + " and col #" + longestCol + ".";
    }
  }
  
}

In the main method, you will need to change the code so it reads:

public class PhraseRunner {
  public static void main(String[] args) {

    // Creates a 2D array of phrases in several sentences
    String[] sentences = { "The quick brown fox", "jumps over the lazy dog", "fox and dog",
                             "Foxes are clever", "but dogs are loyal", "the quick brown fox",
                             "The dog chased the fox", "while the fox jumped", "over the dog" };

    // Calls the countPhrases() method
    System.out.println(PhraseFinder.countPhrases(sentences, "fox"));
    
  }
}

Hope this helps!

Best
-Sam

1 Like

You all are the best!!! This was driving me crazy.

1 Like