CS365 Midterm -- Spring 2021

  1. This exam is open-note, open-book.
  2. You must answer all of the questions.
  3. Cleanness/organization/efficiency of the code matters. When you write code, especially for the last problem, you need to take advantage of Java's language features to produce clean-looking code and you also need to select data structures that will lead to the most efficient execution of the code.
  4. For the coding problems, 4-7, please use "preformatted" text by going to the menu labeled "paragraph" and instead selecting "preformatted". Please indent your code nicely but you only need to use 2 spaces of indentation per "level".
  5. Good luck!

  1. (10 points: Event Handling) For each question below, look at the following list of items and fill in the blank with the best choice(s).
    JFormattedTextFieldJTableJSlider
    JRadioButtonJCheckBoxJButton
    JFrameJPanelJComponent
    JMenuJDialogJContainer

    1. ____________________ The type of component used to create a Java window.

    2. ____________________ The type of widget I should use to allow the user to select a state/territory in the United States. There are roughly 50 states/territories in the US.

    3. ____________________ The type of widget to use when I want the user to enter a social security number with 3 digits, then a dash, then 2 digits, then a dash, and finally 4 digits.

    4. ____________________ The type of widget I should use to show a matrix of data with the rows representing a person and the columns representing information about the person, such as age, salary, name, etc.

    5. ____________________ The type of widget to use if I want to convey a piece of information that should not be altered, such as instructions for entering some piece of data.

  2. (10 points: General content) For each question below, look at the following list of items and fill in the blank with the best choice(s).
    package       extends      import            virtual method
    interface     type         namespaces        generic
    class         finally      final             subtype
    public        Scanner      void              void *
    protected     subclasses   static            generational collector
    composition   inheritance  iterator          stop-and-copy collector
    Error         Throwable    Exception         RuntimeException
    IOException   event        interrupt         non-virtual method
    implements    classpath    include           hotspot compilation
    import        try          throw             reference counting
    catch         friends      polymorphism      mark-and-sweep collector
    Object        union        vtable            setjmp/longjmp

    1. C++ uses _______________________ and ____________________ to implement modules.
    2. __________________ C uses this type to implement generic types.
    3. __________________ How virtual methods are implemented by the compiler.
    4. __________________ The ability of the same code to perform the same action on different types of data.
    5. __________________ A type of garbage collector that explicitly counts the number of pointers to an object so that it can be garbage-collected when there are no longer any pointers to it.

  3. (25 points) You want to write a program that evaluates expression trees, such as:

    Interior nodes are operator nodes, such as +, -, cos, and unary -, and their children may be either operator or operand nodes. Leaf nodes are operand nodes. All nodes contain a variable named value of type double, that is the result of their last evaluation. All nodes also contain a parent pointer to their parent (a parent node is always an Operator node). Operator nodes contain pointers to their children and a boolean variable named upToDate which indicates if their value is up-to-date. There are three types of operator nodes: single operand operators, such as cos and unary -, binary operand operators, such as +, -, *, and /, and n-ary operand operator nodes that can have arbitrarily many operands (remember that operands may be either operator or operand nodes). All nodes have an Evaluate() method that evaluates its operands and returns a double. For example, the Evaluate() method for plus might look like:

    double Evaluate() {	      
      value = child1.getValue() + child2.getValue();
      return value;
    }
    The Evaluate() method for an operand returns the operand's value. Operand nodes have GetValue()/SetValue() methods that allow their value to be retrieved and set. When an Operand's SetValue() method is called, it changes the operand's value and calls the parent's markCacheInvalid method, which recursively chases parent pointers to the root, marking the value of each node it visits as out-of-date. The code for markCacheInvalid might be:
    void markCacheInvalid() {
      upToDate = false;
      if (parent != null) { parent.markCacheInvalid(); }
    }
    
    Operator nodes have a GetValue() method that allows their value to be retrieved. GetValue() checks to see if the cached value is up-to-date and returns it if it is. Otherwise GetValue() calls Evaluate() to update the cached value and then returns the updated value. The code for GetValue() might be:
    double getValue() {
      if (!upToDate) {
        Evaluate();
        upToDate = true;
      } 
      return value;
    }
    
    Operator nodes do not have a SetValue method as their value is determined by their Evaluate method.

    Finally an n-ary operator has two methods named addParameter and removeParameter that add/remove a child from its children list.

    Write the Java code required to create this set of classes. You will need to create one or more additional superclasses that factor out common variables/methods. I want to see:

    1. Class declarations, variable declarations, and method declarations. Do not provide method bodies, except for constructors. I do want to see your constructor bodies. Make sure that any classes and methods that you want to be abstract are declared as abstract and that non-virtual methods are appropriately declared.
    2. Declare PlusOperator as a specific concrete class for a Binary operator. Do not worry about concrete classes for either Unary or n-ary operators and as with the other classes you create, do not provide method bodies, except for the constructor.
    3. Here is a checklist of instance variables and methods that you need to place with the appropriate class(es):
      1. Instance variables: parent, value, upToDate, appropriate children variables that point to children
      2. Methods: Evaluate, markCacheInvalid, GetValue, SetValue, addParameter, removeParameter, and constructors (constructors for unary operators take a single node, constructors for binary operators take two nodes, constructors for n-ary operators take an ArrayList of nodes, and constructors for operands take a double, which is their value).

  4. (10 points: Packages) You have written a program named Appointment and placed it in a package named vaccine. vaccine is in a directory named /gov/tn and Appointment imports a package named gui that is located in a directory named /com/bvz.
    1. Write the java command required to execute Appointment. This command must work regardless of what directory you are in (i.e., you may not assume you are either in the parent directories for your packages or the package directories themselves).

    2. Write the jar command required to jar up Appointment and allow the jar file to execute. The jar file should be named Appointment.jar.

  5. (20 points: Generics) Write a java generic class named Bag. A Bag class takes two type parameters T1 and T2 and has the following instance variables and methods:

    1. Instance variables: It has two Lists named bag1 and bag2, each of which stores one of the two types.
    2. Methods
      1. Something that assigns ArrayLists to bag1 and bag2 when a new Bag object is created. There are multiple ways this might be done, including via a constructor but there are other ways as well.
      2. An add method that takes two parameters of type T1 and T2 and adds the values to their respective lists.
      3. A find method that takes a parameter of type T1 and returns null if the parameter is not found and the corresponding type T2 value if the parameter is found (i.e., if it finds the T1 value at index 5 then it returns the T2 value at index 5 in T2's list). Make sure that you perform a deep rather than a shallow comparison when finding if the parameter exists.

  6. (25 points: Java Basics, Exception Handling) Write a java class named Vote that counts candidate names on ballots submitted by a voter and prints out the candidates' names in ascending order based on their vote count. Your class must meet the following specifications:
    1. The input consists of lines of the form:
      voterName candidate1 candidate2 ... candidaten
      
      Each name is a single word. There must be at least one candidate and there may be as many candidates as the voter wants to list. Do not worry about repeated candidate names.
    2. If a voter tries to vote a second time, throw a RepeatVoterException with the voter's name. Catch the exception and print the error message "voter xxxx has already voted" where xxxx is the name of the voter.
    3. If the ballot does not contain a voterName and at least one candidate name, then print the error message ""ballot xxxx: must have at least one voter and one candidate" where xxxx is the contents of the line containing the missing voterName/candidateName. You are not allowed to use an if statement to check if the voter and candidate names are present. Instead you must read through the line as though the voter/candidate name is present and catch a NoSuchElementElement exception if the names are absent.
    As an example of how the output should look, if the input is:
    brad yifan joe
    sarah
    nels yifan frank sam
    sandy yifan joe brad smiley
    nels brad
        
    then the output should be:
    ballot sarah: must have at least one voter and one candidate
    voter nels has already voted
    frank 1
    brad 1
    sam 1
    smiley 1
    joe 2
    yifan 3
    

    Efficiency matters!!! If you use inefficient data structures or inefficient methods for sorting you will lose points.

    Here is the beginning of the class. Please note that I have written main and the RepeatVoterException classes for you:

    import java.util.*;
    
    class Vote {
        public class RepeatVoterException extends Exception {
    	public String voterName;
    	
    	public RepeatVoterException(String name) {
    	    voterName = name;
    	}
        }
    
        public static void main(String args[]) {
    	new Vote();
        }