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
  • 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...

  • Code in java Using the template below: public class Lab03 { public static void main(String[] args)...

    Code in java Using the template below: public class Lab03 { public static void main(String[] args) { ArrayList<Integer> list1 = new ArrayList<Integer>(); Collections.addAll(list1, 1, 3, 5, 5 ); ArrayList<Integer> list2 = new ArrayList<Integer>(); Collections.addAll(list2, 3, 7, 3, 2, 4 ); ArrayList<Integer> result1= uniqueUnion(list1,list2); System.out.println(result1); Integer[] array = new Integer[]{ 29, 28, 27, 16, 15, -14, 3, -2, 2}; ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(array)); System.out.printf("The average is: %.2f%n", averagePositive(arrayList)); } // end main public static ArrayList<Integer> uniqueUnion(ArrayList<Integer> list1, ArrayList<Integer> list2) {...

  • JAVA 3files seprate 1.Classroom.java 2.ClassroomTester.java (provided) 3.Student.java(provided) Use the following files: ClassroomTester.java import java.util.ArrayList; /** *...

    JAVA 3files seprate 1.Classroom.java 2.ClassroomTester.java (provided) 3.Student.java(provided) Use the following files: ClassroomTester.java import java.util.ArrayList; /** * Write a description of class UniversityTester here. * * @author (your name) * @version (a version number or a date) */ public class ClassroomTester { public static void main(String[] args) { ArrayList<Double> grades1 = new ArrayList<>(); grades1.add(82.0); grades1.add(91.5); grades1.add(85.0); Student student1 = new Student("Srivani", grades1); ArrayList<Double> grades2 = new ArrayList<>(); grades2.add(95.0); grades2.add(87.0); grades2.add(99.0); grades2.add(100.0); Student student2 = new Student("Carlos", grades2); ArrayList<Double> grades3 = new...

  • Complete code and answer question in comments: Package hw4; import java.util.ArrayList; public c...

    Complete code and answer question in comments: Package hw4; import java.util.ArrayList; public class WordGame { /* * Returns all strings that appear * as a consecutive horizontal or vertical sequence of letters * (left-right, right-left, up-down, or down-up) * in the array board and also appear in dict. * Note that the same word may appear multiple times * on the board, and will then be multiple times in * the returned array. * * dict is assumed to be...

  • Language is Java, any help is appreciated. Thank you! WHERE TO START FROM: import java.util.ArrayList; //PartTest.java...

    Language is Java, any help is appreciated. Thank you! WHERE TO START FROM: import java.util.ArrayList; //PartTest.java //package simple; public class PartTest { public static void main(String[] args) { ArrayList<ExpendablePart> system=new ArrayList<ExpendablePart>();   // creating Part Object Part part1 = new ExpendablePart("Last, First"); part1.setNumber("AX-34R"); part1.setNcage("MN34R"); part1.setNiin("ABCD-RF-WDE-KLJM"); // printing information System.out.println(part1.toString());       //Create a part2 object of class Part Part part2=new ConsumablePart("Widget, purple"); part2.setNumber("12345"); part2.setNcage("OU812"); part2.setNiin("1234-12-123-1234");    // printing information System.out.println(part2.toString());    //checking equality of two Part class objects if(part1.equals(part2)) System.out.println("part1 and...

  • Course,java import java.util.ArrayList; import java.util.Arrays; /* * To change this license header, choose License Headers in...

    Course,java import java.util.ArrayList; import java.util.Arrays; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author fenghui */ public class Course {     private String cName;     private ArrayList<Subject> cores;     private ArrayList<Major> majors;     private ArrayList<Subject> electives;     private int cCredit;          public Course(String n, int cc){         cName = n;         cCredit = cc;         cores = new ArrayList<Subject>(0);         majors =...

  • I have the following classes SearchMain.java import java.security.SecureRandom; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** *...

    I have the following classes SearchMain.java import java.security.SecureRandom; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * * DO NOT CHANGE THIS CODE * */ public class SearchMain {    public static void main(String[] args) {        ArraySearcher arraySearch = new ArraySearchImp();        SecureRandom secureRandom = new SecureRandom();        int[] sortedArray = generateRandomSortedIntArray(10);        System.out.println(Arrays.toString(sortedArray));        Set<Integer> intSet = new HashSet<Integer>();               for(int i = 0; i < 5; i++) {       ...

  • package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private...

    package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private static int cardNumber[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; private static char suitName[] = { 'c', 'd', 'h', 's' }; public static void main(String[] args) throws CardException, DeckException, HandException { Scanner kb = new Scanner(System.in); System.out.println("How many Players? "); int numHands = kb.nextInt(); int cards = 0; if (numHands > 0) { cards = 52 / numHands; System.out.println("Each player gets " + cards + " cards\n"); } else...

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