Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Complete the class code below and include a method named \"search\" that takes t

ID: 3817114 • Letter: C

Question

Complete the class code below and include a method named "search" that takes two String parameters, a string to search and the other a target string to search for in the first string. The search method will return an integer representing the number of times the search string was found. The string being searched is a super-string formed by joining all lines of a text file, so we might expect to get multiple hits with our method. public class WordSearch { public static void main(String[] args) { String fileName = "story.txt"; String target = "help"; Scanner fileIn = new Scanner(new File(fileName)); String story = ""; while(fileIn.hasNextLine()) { story += fileIn.nextLine(); // Build a super-String } System.out.println("(" + target + ") found " + search(story, target) + " times"); } // method code here } // end of WordSearch class

Explanation / Answer

WordSearch class

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class WordSearch {

   public static void main(String[] args) throws FileNotFoundException

   { String fileName = "story.txt";

   String target = "aiva";

   Scanner fileIn = new Scanner(new File(fileName));

   String story = "";

   while(fileIn.hasNextLine())

   {

       story += fileIn.nextLine(); // Build a super-String

   }

       fileIn.close();       //Closed the scanner

       System.out.println("(" + target + ") found " + search(story, target) + " times");

   } // method code here

   private static int search(String story, String target) {

       int count=0;

       int targetLength = target.length();

       for(int i=0;i<story.length();i++)

       {

           if(story.length()>=i+targetLength)

           if(story.substring(i, i+targetLength).equals(target))

               count++;

       }

       return count;

   }

} // end of WordSearch class

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote