Question

In: Computer Science

 This homework will check your ability to declare and use classes and object, and how...

 This homework will check your ability to declare and use classes and object, and how to use both Maps and sets in Java. The assignment will also serve as an introduction to Junit Testing.

 Here is the general layout. Some more detailed instructions are also included below. Pay attention to the details and the naming conventions, since we will be running your code through testing code the grading team will develop. That code will require your method signatures to be consistent with these instructions.

 Please call your project LegislatorFinder

 inside your project, please have a package called LegislatorFinder

 create your java files inside the LegislatorFinder package.

 We will be simulating the system by which people can find who their legislators are:

There is a class called Legislator, with the following attributes: ▪ lastName ▪ firstName ▪ politicalParty ▪ Each of those attributes has getter and setter functions therefore, this class has the following methods:  getLastName(),  getFirstName,  getPoliticalParty(),  setFirstName(string),  setLatName(string),  setPoliticalParty(string) ▪ in addition, the class has two constructors:  one with no arguments.  One that takes arguments string, string, string

There is a class called LegislatorFinder ▪ this class has only one attribute, a TreeMap ▪ for methods, you should implement  addLegislator(string state, Legislator l) ◦ if the state already exists in the TreeMap, it adds this legislator to the set the state maps to. ◦ If the state doe not exist in the TreeMap, it adds a new key:value pair to the map, with this legislator in the corresponding set.  getLegislators(string state) ◦ returns the set of legislators from the given state. If there is no such state key in the map, returns an empty set.  substituteLegislators(String state, Set newLegislators) ◦ substitutes the legislators for the indicated state with the one in newLegislators. If there was no such state key in the Map, it creates a new key:value pair. If there was a key:value pair for this state already, it substitutes the previous set of legislators with the one passed as an input parameter.

◦ Through JUnit tests, test the following operations: ▪ adding legislators, both for a state key that is already in the map, and for a state key not yet in the map. ▪ Retrieving legislators, both for a state key that is already in the map, and for a state key not yet in the map. ▪ Substituting the set of legislators for a given state for the following cases:  the state was not previously being used as a key in the map.  The key was being used as a key in the map.

(Need to implement a TreeMap method)

Solutions

Expert Solution

Hi,

Please find the below code according to the given requirements.

***************************************************************************

Legislator.java

***************************************************************************

package LegislatorFinder;

public class Legislator {
  
   private String firstName;
   private String lastName;
   private String politicalParty;
   /**
   *
   */
   public Legislator() {
       firstName="";
       lastName="";
       politicalParty="";
   }
   /**
   * @param firstName
   * @param lastName
   * @param politicalParty
   */
   public Legislator(String firstName, String lastName, String politicalParty) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.politicalParty = politicalParty;
   }
   /**
   * @return the firstName
   */
   public String getFirstName() {
       return firstName;
   }
   /**
   * @param firstName the firstName to set
   */
   public void setFirstName(String firstName) {
       this.firstName = firstName;
   }
   /**
   * @return the lastName
   */
   public String getLastName() {
       return lastName;
   }
   /**
   * @param lastName the lastName to set
   */
   public void setLastName(String lastName) {
       this.lastName = lastName;
   }
   /**
   * @return the politicalParty
   */
   public String getPoliticalParty() {
       return politicalParty;
   }
   /**
   * @param politicalParty the politicalParty to set
   */
   public void setPoliticalParty(String politicalParty) {
       this.politicalParty = politicalParty;
   }   

}

***************************************************************************

LegislatorFinder.java

***************************************************************************

package LegislatorFinder;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeMap;

public class LegislatorFinder {
  
   TreeMap<String,Set<Legislator>> legislators = new TreeMap<>();
  
   //creating a dummy database for testing
   public LegislatorFinder() {
       Legislator l1 = new Legislator("ajay", "kumar", "INC");
       Legislator l2 = new Legislator("Narendra", "Modi", "BJP");
       Legislator l3 = new Legislator("Rahul", "Gandhi", "INC");
       Legislator l4 = new Legislator("Sushma", "Swaraj", "BJP");
       Legislator l5 = new Legislator("Amit", "Shah", "BJP");
       Legislator l6 = new Legislator("Uttam", "Kumar", "INC");
      
       Set<Legislator> set1 = new HashSet<>();
       set1.add(l1);
       set1.add(l2);
       set1.add(l5);
      
       legislators.put("Delhi", set1);
      
       Set<Legislator> set2 = new HashSet<>();
       set1.add(l3);
       set1.add(l4);
       set1.add(l6);
      
       legislators.put("Gujarat", set2);
      
   }
  
   public void addLegislator(String state,Legislator l) {
       Set<String> keys = legislators.keySet();
      
       if(keys.contains(state)) {
           legislators.get(state).add(l);
       }
       else {
           Set<Legislator> lgSet = new HashSet<>();
           lgSet.add(l);
           legislators.put(state, lgSet);
       }
      
   }
  
   public Set<Legislator> getLegislator(String state){
       Set<String> keys = legislators.keySet();
       for(String s : keys) {
           if(state.equals(s)) {
               return legislators.get(s);
           }
       }
       return null;
      
   }
  
   public void substituteLegislators(String state, Set<Legislator> newLegislators) {
       Set<String> keys = legislators.keySet();
       if(keys.contains(state)) {
           legislators.put(state, newLegislators);
       }else {
           legislators.put(state, newLegislators);
       }
      
   }

}

***************************************************************************

LegislatorTest.java

***************************************************************************

package LegislatorFinder;

import java.util.Set;
import java.util.TreeMap;

import org.junit.Test;

import static org.junit.Assert.*;

public class LegislatorTest {
  
   @Test
   public void testAddIfKeyExists() {
      
       LegislatorFinder finder = new LegislatorFinder();
       TreeMap<String,Set<Legislator>> legislators = finder.legislators;
       Set<String> keys = legislators.keySet();
       String expected = "Delhi";
       assertTrue(keys.contains(expected));
      
   }
  
   @Test
   public void testAddIfKeyNotExists() {
      
       LegislatorFinder finder = new LegislatorFinder();
       TreeMap<String,Set<Legislator>> legislators = finder.legislators;
       Set<String> keys = legislators.keySet();
       String expected = "Telangana";
       assertFalse(keys.contains(expected));
      
   }

   @Test
   public void testGetExistingKey() {
      
       LegislatorFinder finder = new LegislatorFinder();
       String expected = "Delhi";
       assertNotNull((finder.getLegislator(expected)));
      
   }
  
   @Test
   public void testGetNonExistingKey() {
      
       LegislatorFinder finder = new LegislatorFinder();
       String expected = "MP";
       assertNull((finder.getLegislator(expected)));
      
   }
  
   @Test
   public void testSubstituteForUsedKey() {
      
       LegislatorFinder finder = new LegislatorFinder();
       TreeMap<String,Set<Legislator>> legislators = finder.legislators;
       Set<String> keys = legislators.keySet();
       String expected = "Delhi";
       assertTrue(keys.contains(expected));
      
   }
  
   @Test
   public void testSubstituteForKeyNotUsed() {
      
       LegislatorFinder finder = new LegislatorFinder();
       TreeMap<String,Set<Legislator>> legislators = finder.legislators;
       Set<String> keys = legislators.keySet();
       String expected = "Telangana";
       assertFalse(keys.contains(expected));
      
   }
}

Output:

Hope this helps!!


Have a good day


Related Solutions

How algorithms address object-oriented classes and objects. What is the File object? How are File objects...
How algorithms address object-oriented classes and objects. What is the File object? How are File objects used in algorithms? 175 words minumum please :)
Create an object called Circle. Declare the following integer variables for the object Circle, radius, diameter,...
Create an object called Circle. Declare the following integer variables for the object Circle, radius, diameter, and pi is declared as double. Create the following for the Circle object: ● Implicit constructor (default constructor) ● Void method Calculate (double pi, int radius) to calculate the area of the Circle object. The method must include a system.out statement that displays the area value. Use the following formula to calculate area of the circle: Area = pi * (r * r) Your...
4. For each of the following haskell type declarations, declare an object of the type this....
4. For each of the following haskell type declarations, declare an object of the type this. a. type this = ([Bool], Float) b. type this = (Float, Integer) -> ([Float], Integer) c. data that = new Char | old Integer type this = [(Float, that)] d. type this = (a, b) -> (a, a)
Rewrite your program for part 1. Do not declare the array globally, declare it in the...
Rewrite your program for part 1. Do not declare the array globally, declare it in the loop function. This now requires that you add two parameters to your fill array and print array functions. You must now pass the array name and array size as arguments, when the program calls these functions. The program has the same behavior as problem 1, but illustrates the difference between globally and locally declared variables. The program code for part 1 was: int Array[15]...
FlashCards with Classes and Exception Handling – Project Project Overview Create at least 2 object classes...
FlashCards with Classes and Exception Handling – Project Project Overview Create at least 2 object classes (Session and Problems) and one driver class and ensure the user inputs cannot cause the system to fail by using exception handling. Overview from Project . Implement a Java program that creates math flashcards for elementary grade students. User will enter his/her name, the type (+,-, *, /), the range of the factors to be used in the problems, and the number of problems...
// Lab Homework 11 // Logical Operator AND and OR // Demonstrate how to use a...
// Lab Homework 11 // Logical Operator AND and OR // Demonstrate how to use a logical operator // with a Boolean expression. #include <iostream> #include <cctype> // for tolower() using namespace std; int main() {    int numberOfCreditHours; // Number of credit hours student has completed    float gpa; // The student's cumulative grade point average    // Ask the user two questions:    cout << "Answer the following questions:" << endl << endl;    cout << "How many...
Homework 3 – Programming with C++ What This Assignment Is About: • Classes and Objects •...
Homework 3 – Programming with C++ What This Assignment Is About: • Classes and Objects • Methods • Arrays of Primitive Values • Arrays of Objects • Recursion • for and if Statements • Insertion Sort 2. Use the following Guidelines • Give identifiers semantic meaning and make them easy to read (examples numStudents, grossPay, etc). • User upper case for constants. Use title case (first letter is upper case) for classes. Use lower case with uppercase word separators for...
Python HW with Jupyter Notebook Declare a variable named DATA as a dictionary object. Assign the...
Python HW with Jupyter Notebook Declare a variable named DATA as a dictionary object. Assign the set of key/value pairs shown below. Create a function named iter_dict_funky_sum() that takes one dictionary argument.    Declare a running total integer variable. Extract the key/value pairs from DATA simultaneously in a loop. Do this with just one for loop and no additional forms of looping. Assign and append the product of the value minus the key to the running total variable. Return the funky...
C++ Please complete based on the code below. Declare another stack object to the code in...
C++ Please complete based on the code below. Declare another stack object to the code in main(). Add a stack operator called CopyStack to the Stack class which, when executed, copies the contents of the first stack into the second stack. Modify your menu so that this option is available. The menu should also allow the second stack to be printed, pushed, popped, and so forth, just like with the first stack. #include using namespace std; #define MAXSize 10 class...
This task exercises your ability to use python to represent data and use flow control and...
This task exercises your ability to use python to represent data and use flow control and functions to re-organize the data. You need to submit the ipynb file to Moodle. A data scientist has collected tube information and saved the video info in multiple CSV files. Each CSV file has the following columns: ·         video_id ·         trending_date ·         title ·         channel_title ·         category_id ·         publish_time ·         tags ·         views    ·         likes      ·         dislikes ·         comment_count ·         thumbnail_link ·         comments_disabled     ·         ratings_disabled          ·         video_error_or_removed        ·         description You are asked to write python code to process CSV data...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT