Question

JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...

JAVA programming

9.9 Ch 9, Part 2: ArrayList Searching

import java.util.ArrayList;

public class ArrayListSet {

    /**
     * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList
     * containing all the indexes of Strings in arr that match String s. For this method, two Strings,
     * p and q, match when p.equals(q) returns true or if both of the compared references are null.
     *
     * @param s The string to search for.
     * @param arr The ArrayList of string to search.
     * @return An ArrayList of the indexes in arr that match s. The ArrayList will be ordered from
     *         the smallest index to the largest. If arr is null, the method will return null.
     */
    public static ArrayList<Integer> findExact(String s, ArrayList<String> arr) {
        return null;
    }

    /**
     * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList
     * containing all the indexes of Strings in arr that contains String s. For this method, a
     * Strings p contains q when p.contains(q) returns true or if both of the compared references are null.
     *
     * @param s The string to search for.
     * @param arr The ArrayList of string to search.
     * @return An ArrayList of the indexes in arr that contains s. The ArrayList will be ordered from
     *         the smallest index to the largest. If arr is null, the method will return null.
     */
    public static ArrayList<Integer> findContains(String s, ArrayList<String> arr) {
        return null;
    }

    /**
     * Adds String s to the end of the ArrayList arr if and only if arr does not already have an
     * element that matches s.
     *
     * Do not duplicate code! Use your findExact method to check if arr contains s.
     *
     * @param s The string to add (if not already in arr).
     * @param arr The ArrayList in which to s (if a String with the same contents is not already in
     *            arr).
     * @return The number of times that s is found in arr after attempting to adding s. If arr is null,
     *         return -1.
     */
    public static int addUniqueString(String s, ArrayList<String> arr) {
        return -42;
    }

}

import java.util.ArrayList;
import java.util.Arrays;

public class TestArrayListSet {

    public static boolean testFindExact() {
        System.out.println("Starting testFindExact...");
        //Test 1
        {
            ArrayList<Integer> ret =
                ArrayListSet.findExact("foo", new ArrayList<String>(Arrays.asList("foo","bar","foo")));
            ArrayList<Integer> exp = new ArrayList<Integer>(Arrays.asList(0, 2));
            if(!ret.equals(exp)) {
                System.out.println("Test 1 failed!");
                System.out.println("Returned: " + ret);
                System.out.println("Expected: " + exp);
                return false;
            }
        }
        System.out.println("...Done testFindExact");
        return true;
    }

    public static boolean testFindContains() {
        System.out.println("Starting testFindContains...");
        //Test 1
        {
            ArrayList<Integer> ret =
                ArrayListSet.findContains("o", new ArrayList<String>(Arrays.asList("foo","bar","foo")));
            ArrayList<Integer> exp = new ArrayList<Integer>(Arrays.asList(0, 2));
            if(!ret.equals(exp)) {
                System.out.println("Test 1 failed!");
                System.out.println("Returned: " + ret);
                System.out.println("Expected: " + exp);
                return false;
            }
        }
        System.out.println("...Done testFindContains");
        return true;
    }

    public static boolean testAddUniqueString() {
        System.out.println("Starting testAddUniqueString...");
        //Test 1
        {
            ArrayList<String> arr = new ArrayList<String>(Arrays.asList("a","b","c"));
            ArrayList<String> exp = new ArrayList<String>(arr);
            exp.add("d");
            int retIndex = ArrayListSet.addUniqueString("d", arr);
            int expIndex = 1;
            if(!arr.equals(exp) || retIndex != expIndex) {
                System.out.println("Test 1 failed!");
                System.out.println("Returned value: " + retIndex + "; expected " + expIndex);
                System.out.println("List after: " + arr);
                System.out.println("Expected: " + exp);
                return false;
            }
        }
        //Test 2
        {
            ArrayList<String> arr = new ArrayList<String>(Arrays.asList("a","b","b","c"));
            ArrayList<String> exp = new ArrayList<String>(arr);
            int retIndex = ArrayListSet.addUniqueString("b", arr);
            int expIndex = 2;
            if(!arr.equals(exp) || retIndex != expIndex) {
                System.out.println("Test 2 failed!");
                System.out.println("Returned value: " + retIndex + "; expected " + expIndex);
                System.out.println("List after: " + arr);
                System.out.println("Expected: " + exp);
                return false;
            }
        }
        System.out.println("...Done testAddUniqueString");
        return true;
    }
  
    public static void main(String[] args) {
        testFindExact();
        testFindContains();
        testAddUniqueString();
    }
  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Given below is the code for the question. Run the TestArrayListSet.java provided by instructor.
Please do rate the answer if it helped. Thank you.


import java.util.ArrayList;

public class ArrayListSet {

/**
* Searches through the ArrayList arr, from the first index to the last, returning an ArrayList
* containing all the indexes of Strings in arr that match String s. For this method, two Strings,
* p and q, match when p.equals(q) returns true or if both of the compared references are null.
*
* @param s The string to search for.
* @param arr The ArrayList of string to search.
* @return An ArrayList of the indexes in arr that match s. The ArrayList will be ordered from
* the smallest index to the largest. If arr is null, the method will return null.
*/
public static ArrayList<Integer> findExact(String s, ArrayList<String> arr) {
   if(arr == null)
       return null;
   ArrayList<Integer> indices = new ArrayList<Integer>();
   for(int i = 0; i < arr.size(); i++) {
       if((s == null && arr.get(i) == null) || s.equals(arr.get(i)))
           indices.add(i);
   }
return indices;
}

/**
* Searches through the ArrayList arr, from the first index to the last, returning an ArrayList
* containing all the indexes of Strings in arr that contains String s. For this method, a
* Strings p contains q when p.contains(q) returns true or if both of the compared references are null.
*
* @param s The string to search for.
* @param arr The ArrayList of string to search.
* @return An ArrayList of the indexes in arr that contains s. The ArrayList will be ordered from
* the smallest index to the largest. If arr is null, the method will return null.
*/
public static ArrayList<Integer> findContains(String s, ArrayList<String> arr) {
   if(arr == null)
       return null;
  
   ArrayList<Integer> indices = new ArrayList<Integer>();
   for(int i = 0; i < arr.size(); i++) {
       if((arr.get(i) == null && s == null) || (arr.get(i) != null && arr.get(i).contains(s)) )
           indices.add(i);
   }
return indices;
}

/**
* Adds String s to the end of the ArrayList arr if and only if arr does not already have an
* element that matches s.
*
* Do not duplicate code! Use your findExact method to check if arr contains s.
*
* @param s The string to add (if not already in arr).
* @param arr The ArrayList in which to s (if a String with the same contents is not already in
* arr).
* @return The number of times that s is found in arr after attempting to adding s. If arr is null,
* return -1.
*/
public static int addUniqueString(String s, ArrayList<String> arr) {
   ArrayList<Integer> idx = findExact(s, arr);
   if(idx == null)
       return -1;
   if(idx.isEmpty())
   {
       arr.add(s);
       return 1;
   }
   else
       return idx.size();
}

}


output
---
Starting testFindExact...
...Done testFindExact
Starting testFindContains...
...Done testFindContains
Starting testAddUniqueString...
...Done testAddUniqueString

Add a comment
Know the answer?
Add Answer to:
JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */    public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null;...

  • Need Help Using Java programming only import java.util.ArrayList; //Import anything you need here public class Dictionary...

    Need Help Using Java programming only import java.util.ArrayList; //Import anything you need here public class Dictionary {     // Declare any variables you feel necessary here     public Dictionary(/*DO NOT PUT ANY PARAMETERS HERE!*/) {         // Initialise those variables     }     /***      * @return number of terms currently in the dictionary hint: starts at 0 when      *         there are no terms      */     public int numberOfTerms() {         return 0;     }     /***     ...

  • Please help with Java array list: import java.util.ArrayList; public class ListUpdate { /** * Does a...

    Please help with Java array list: import java.util.ArrayList; public class ListUpdate { /** * Does a linear search through the ArrayList list, returning the index of the first occurrence of * valToFind. * * Starting from index 0, check each element in list and return the index of the first element * that matches valToFind. * * @param valToFind The int value to search for. * @param list The ArrayList of Integers to search in. * @return The index of...

  • public class F2{ public static int foo(ArrayList<Integer> a) { int sum = 0; for(int i =...

    public class F2{ public static int foo(ArrayList<Integer> a) { int sum = 0; for(int i = 0; i <a.size(); i++){ if(i % 3 == 1) sum += a.get(i); else if(i % 3 == 2) sum -= a.get(i); else sum++; } return sum; } } What do the following method calls return? 1. foo(new ArrayList<>(Arrays.asList(1,2,3,4))) 2. foo(new ArrayList<>()) 3. foo(new ArrayList<>(Arrays.asList(1,2,-3,4325,-2))) 4. foo(new ArrayList<>(Arrays.asList(0,0,0)))

  • import java.util.Random; import java.util.ArrayList; /** * */ public class hw5_task8 { public static void main(String[] args)...

    import java.util.Random; import java.util.ArrayList; /** * */ public class hw5_task8 { public static void main(String[] args) { int[] grades = randomIntArr(10); printIntArray("grades", grades); ArrayList<Integer> indexesF_AL = selectIndexes_1(grades); System.out.println(" indexesF_AL: " + indexesF_AL); int[] indexesF_Arr = selectIndexes_2(grades); printIntArray("indexesF_Arr",indexesF_Arr); } public static int[] randomIntArr(int N){ int[] res = new int[N]; Random r = new Random(0); for(int i = 0; i < res.length; i++){ res[i] = r.nextInt(101); // r.nextInt(101) returns an in in range [0, 100] } return res; } public static void...

  • Hello, I've been working on this for a while and I can't figure the rest out....

    Hello, I've been working on this for a while and I can't figure the rest out. Need asap if anyone can help. maxBSt,minBST,isBST, and inOrder package lab7; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class TreeExercise {    /*    * Construct BST from preorder traversal    */    public static Node<Integer> consBSTfromPreOrder(int[] arr, int start, int end)    {                       if(start > end) return null;               Node<Integer> root = new Node<Integer>(arr[start],...

  • PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class...

    PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class definition. * * @author David Brown * @version 2019-01-22 */ public class Movie implements Comparable { // Constants public static final int FIRST_YEAR = 1888; public static final String[] GENRES = { "science fiction", "fantasy", "drama", "romance", "comedy", "zombie", "action", "historical", "horror", "war" }; public static final int MAX_RATING = 10; public static final int MIN_RATING = 0; /** * Converts a string of...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Finds the specified set of words in the specified file and returns them * as an ArrayList. This finds the specified set in the file which is on the * line number of the set. The first line and set in the file is 1. * * This returns an ArrayList with the keyword first, then : and then followed...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */ public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null; //TODO...

  • /** * */ package groceries; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ShoppingList {   ...

    /** * */ package groceries; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ShoppingList {    /**    * @param args    */    public static void main(String[] args) {        List groceryList = new ArrayList<>();        groceryList.add("rice");        groceryList.add("chicken");        groceryList.add("cumin");        groceryList.add("tomato");        groceryList.add("cilantro");        groceryList.add("lime juice");        groceryList.add("peppers");               groceryList.remove("cilantro");               for (int i = 0; i            if (groceryList.get(i).equals("peppers")) {...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT