Question

**** ITS MULTI-PART QUESTION. PLEASE MAKE SURE TO ANSWER THEM ALL. SOLVE IT BY JAVA. ****...

**** ITS MULTI-PART QUESTION. PLEASE MAKE SURE TO ANSWER THEM ALL. SOLVE IT BY JAVA. ****

*** ALSO MAKE SURE IT PASS THE TESTER FILE PLEASE***

Often when we are running a program, it will have a number of configuration options which tweak its behavior while it's running. Allow text completion? Collect anonymous usage data? These are all options our programs may use. We can store these options in an array and pass it to the program. In its simplest form, we can imagine that if an option shows up in the array, then it is set, and if it does not show up in the array, then it is not set.

Our first task is to encode an Option class, which has a key which identifies it within an options list (an array of strings). That is, if the key is in the options list, then the option is considered to be set. The class will implement the code which detects whether the option is found, along with some supporting functionality.

Any data elements should be declared private. If you think it is necessary you may include helper methods of your own. The class should implement the following public methods:

  • public Option(String key, String name) Initialize an option which will be recognized using the given key, and which has a full English description given in name. For example, we can have an option identified in a list of options (an array of strings) by the key "s1" and have the name "Switch number 1".
  • public boolean isFound() Reports the value of a flag indicating whether or not the option has been found yet. The flag begins as false, but will change to true if the option is found at some point in the string array (options list).
  • public String getKey() A getter which will return the value of the key string.
  • public String getName() A getter which will return the value of the name string.
  • public int numSlots() The number of slots taken up by this option within a string array (options list). This will return 1 (but we can imagine that if we were to include attribute values, it could be more).
  • public boolean match(String[] s, int i) Checks the option at position i of string array (options list) s to see if it's the same option (meaning that the option is found), and if so, set the internal flag to true. Return true or false depending on whether there was a match. For example:

    > Option o = new Option("mode_priv", "Private browsing");
    > String[] s = {"no_cookies", "mode_priv", "java_enabled"};
    > System.out.println(o.isFound());
    false
    > System.out.println(o.match(s, 0));
    false
    > System.out.println(o.match(s, 1));
    true
    > System.out.println(o.isFound());
    true

  • @Override public String toString() Returns the name of the option, followed by a colon, space, and either "yes" or "no" depending on whether the option was found. For example:

    > Option o = new Option("d", "Debug mode");
    > System.out.println(o);
    Debug mode: no

Now, we will write an OptionProcessor class which collects several Options, and uses it to detect which ones of those options are found within a given string array (options list). So imagine that we have three Option objects, "Option 1" (with key "o1"), "Option 2" (with key "o2"), and "Option 3" (with key "o3"), and we are handed an options list {"o2", "o1"}. We would look at the list and see that Option 1 and Option 2 are set, while Option 3 is not set (it's not part of the list). This class will have a process()method which goes through the provided list one by one in order to determine which of our stored Options are part of the list. Thus, by the end of the array, we would know which options are set and which are not.

The class should implement the following public methods:

  • public OptionProcessor() Initialize an option processor with no available built-in options.
  • public void add(Option o) Add a type of Option to be checked for in a string array (options list).
  • public void process(String[] input) Process the options list contained in input, using the selection of possible Options which have been added previously, to determine which options are set. Example:

    > OptionProcessor op = new OptionProcessor();
    > op.add(new Option("4wd", "Four wheel drive"));
    > op.add(new Option("bswarn", "Blind spot warning"));
    > op.add(new Option("ebr", "Emergency braking"));
    > op.add(new Option("xwarn", "Rear cross-traffic warning"));
    > op.add(new Option("nav", "Navigation system"));
    > String[] oplist = {"bswarn", "xwarn", "ebr", "nav"};
    > op.process(oplist);
    > System.out.println(op.toString());
    Four wheel drive: no
    Blind spot warning: yes
    Emergency braking: yes
    Rear cross-traffic warning: yes
    Navigation system: yes

    Here is a suggested approach to do this: we would want to first start at the begining of input the list, and continue until we've checked everything in the list. At every position, check each of the stored Option objects to see if there is a match. If so, move the position forward by numSlots() (which is just 1 position forward for ordinary Options, but we'll see later why we may want to skip more places for other types of Option). If no Option matches at the current position, then skip it and move on to the next position.
  • @Override public String toString() Returns the concatenation of the toString() output of each of the stored Option objects, separated by newlines. See above.

Now, we will write the StringOption class which extends Option. Did you wonder why we needed the numSlots() method in Option, or why we incremented by numSlots() in OptionProcessor.process()? It's because sometimes we have some kind of attributes associated with an option. For example, we may have a name option which has an additional field which stores the actual name. We will do this by using two spots in the string array (options list), where the first one identifies the option as before, while the second one is the text associated with the option. So where our "Option 1" may have shown up as {"op1"} in a string array (options list), we may have a "Name" option which shows up as {"n", "George Mason"}. Our StringOption class uses an extra member to store the text attribute associated with the option. Since we have already written Option and we have the power of inheritance at our disposal, we do not need to do too much to make this work.

The class should implement the following public methods:

  • public StringOption(String key, String name, String defValue) Initialize the key and name as before, but now, since we have an attribute value as well, use defValue to indicate the default value of the attribute.
  • @Override public int numSlots() This should return 2 (instead of 1 like before - now we use two slots in the string array (options list), because the second slot is the attribute value).
  • public String getValue() A getter which returns the attribute value
  • @Override public boolean match(String[] s, int i) Now, in addition to what the method did previously, if the option matches it should save the attribute value from index i+1 of the array.
  • @Override public String toString() This should behave like the parent's toString(), except that instead of printing yes or no, it should print the text of the attribute.
  • https://mason.gmu.edu/~iavramo2/classes/cs211/s19/E6tester.java
0 0
Add a comment Improve this question Transcribed image text
Answer #1

E6tester.java

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;

public class E6tester {
public static void main(String args[]){
    org.junit.runner.JUnitCore.main("E6tester");
}

@Test public void option_construct() {
    Option o = new Option("op1", "Option 1");
    assertEquals("incorrect key value", "op1", o.getKey());
    assertEquals("incorrect option name", "Option 1", o.getName());
    assertEquals("number of slots should be 1", 1, o.numSlots());
    assertFalse("isFound() should initially be false", o.isFound());
}

@Test public void option_match() {
    for (int i = 0; i < 5; i++) {
      String[] s = {"y", "n", "y", "y", "n"};
      boolean expected = s[i].equals("y");
      Option o = new Option("y", "test option");
      String errMsg = String.format("improper match detection at position %d of %s", i, Arrays.toString(s));
      assertEquals(errMsg, expected, o.match(s, i));
      errMsg = String.format("incorrect isFound() output after position %d of %s", i, Arrays.toString(s));
      assertEquals(errMsg, expected, o.isFound());
      String expectStr = String.format("test option: %s", (expected ? "yes" : "no"));
      errMsg = String.format("incorrect toString() output after position %d of %s", i, Arrays.toString(s));
      assertEquals(errMsg, expectStr, o.toString());
    }
}

@Test public void optionprocessor_construct() {
    OptionProcessor op = new OptionProcessor();
    assertEquals("OptionProcessor should initially have an empty toString()", "", op.toString());
}

@Test public void optionprocessor_add() {
    OptionProcessor op = new OptionProcessor();
    String expected = "";
    for (int i = 0; i < 5; i++) {
      op.add(new Option("op" + i, "Option " + i));
      expected += String.format("Option %d: no\n", i);
    }
    assertEquals("incorrect output from adding Options", expected, op.toString());
}

@Test(timeout=1000) public void optionprocessor_process() {
    String[] opList = {"op1", "op0", "op5", "op4"};
    boolean[] expected = {true, true, false, false, true, true, false, false};
    String expString = "";
    Option[] optObjs = new Option[8];
    OptionProcessor op = new OptionProcessor();
    for (int i = 0; i < optObjs.length; i++) {
      optObjs[i] = new Option("op" + i, "Option " + i);
      op.add(optObjs[i]);
      expString += String.format("Option %d: %s\n", i, (expected[i] ? "yes" : "no"));
    }
    op.process(opList);
    String errMsg = String.format("incorrect result of processing options list %s", Arrays.toString(opList));
    assertEquals(errMsg, expString, op.toString());  
}

@Test(timeout=1000) public void optionprocessor_skipopt() {
    String[] opList = {"unknown", "op0"};
    boolean[] expected = {true, false};
    String expString = "";
    Option[] optObjs = new Option[expected.length];
    OptionProcessor op = new OptionProcessor();
    for (int i = 0; i < optObjs.length; i++) {
      optObjs[i] = new Option("op" + i, "Option " + i);
      op.add(optObjs[i]);
      expString += String.format("Option %d: %s\n", i, (expected[i] ? "yes" : "no"));
    }
    op.process(opList);
    String errMsg = String.format("incorrect result of processing options list %s", Arrays.toString(opList));
    assertEquals(errMsg, expString, op.toString());  
}

@Test public void stringoption_construct() {
    StringOption o = new StringOption("op1", "Option 1", "default");
    assertTrue("StringOption should inherit from Option", o instanceof Option);
    assertEquals("incorrect key value", "op1", o.getKey());
    assertEquals("incorrect option name", "Option 1", o.getName());
    assertEquals("incorrect option attribute value", "default", o.getValue());
    assertEquals("number of slots should be 2", 2, o.numSlots());
    assertFalse("isFound() should initially be false", o.isFound());
}

@Test public void stringoption_match() {
    for (int i = 0; i < 5; i++) {
      int j = 2*i;
      String[] s = {"y", "s0", "n", "s1", "y", "s2", "y", "s3", "n", "s4"};
      boolean expected = s[j].equals("y");
      StringOption o = new StringOption("y", "test option", "def value");
      String errMsg = String.format("improper match detection at position %d of %s", j, Arrays.toString(s));
      assertEquals(errMsg, expected, o.match(s, j));
      errMsg = String.format("incorrect isFound() output after position %d of %s", j, Arrays.toString(s));
      assertEquals(errMsg, expected, o.isFound());
      String expectStr = String.format("test option: %s", (expected ? "s"+i : "def value"));
      errMsg = String.format("incorrect toString() output after position %d of %s", j, Arrays.toString(s));
      assertEquals(errMsg, expectStr, o.toString());
    }
}

@Test(timeout=1000) public void stringoption_process() {
    String[] opList = {"sop1", "s1", "op0", "sop5", "s5", "op4"};
    boolean[] expFound = {true, true, false, false, true, true, false, false};
    String[] expValue = {"yes", "s1", "no", "def3", "yes", "s5", "no", "def7"};
    String expString = "";
    Option[] optObjs = new Option[8];
    OptionProcessor op = new OptionProcessor();
    for (int i = 0; i < optObjs.length; i++) {
      if (i%2 == 0) {
        optObjs[i] = new Option("op" + i, "Option " + i);
        expString += String.format("Option %d: %s\n", i, expValue[i]);
      }
      else {
        optObjs[i] = new StringOption("sop" + i, "String Option " + i, "def" + i);
        expString += String.format("String Option %d: %s\n", i, expValue[i]);
      }
      op.add(optObjs[i]);
    }
    op.process(opList);
    String errMsg = String.format("incorrect result of processing options list %s", Arrays.toString(opList));
    assertEquals(errMsg, expString, op.toString());  
}

}

Option.java

public class Option {
    // Declare variable
    private String key;
    private String name;
    private boolean keyFound;
    private String fullStr;
    // Constructor to initialize
    public Option(String key, String name) {
        this.key=key;
        this.name=name;
        this.keyFound=false; // initialize as false
        this.fullStr="";
    }
    // getter method for keyFound
    public boolean isFound(){
        return this.keyFound;
    }
    // getter for key
    public String getKey() {
        return this.key;
    }
    // getter for name
    public String getName(){
        return this.name;
    }
    // return numSlots as 1
    public int numSlots(){
        return 1;
    }
    public boolean match(String[] s, int i) {
        if (i<=s.length-1){ // Make sure i is not out of range
            // If key found set it to true
            if (s[i].equals(this.key)) {
                this.keyFound = true;
            }
            // If not, set it to false
            else {this.keyFound=false;}
        }
        return this.keyFound;
    }
    @Override public String toString() {
        // create string as shown formatted and return fullString
        if (this.keyFound) {
            this.fullStr= String.format("%s: yes",this.name);
        }
        else {
            this.fullStr= String.format("%s: no",this.name);
        }
        return this.fullStr;
    }
}

OptionProcessor.java

// import ArrayList to use its method
import java.util.ArrayList;
public class OptionProcessor {
    // Declare variables, ArrayList type Option class
    private ArrayList<Option> opt;
    private String fullStr;
    public OptionProcessor() {
        // Initialize under the constructor
        this.opt= new ArrayList<Option>();
        this.fullStr="";
    }
    public void add(Option o) {
        this.opt.add(o); // appending object to the ArrayList
    }
    public void process(String[] inputs) {
        for (Option a:opt) { // go through every elements in ArrayList
            // using nested loop to compare every element
            for (int b=0; b<inputs.length; b++) {
                // brreak if key found
                if (a.match(inputs, b)) {break;};
            }
        }
    }
    @Override public String toString() {
        // go through every element in the ArrayList and append it to String
        // /n to get newline after each element
        for (Option c:opt) {
            this.fullStr += c.toString() +"\n";
        }
        return this.fullStr;
    }
}

StringOption.java

// sub class, in heritance from Option (parents class)
public class StringOption extends Option {
    // Declare variable
    private String defValue;
    // Constructor to initialize
    public StringOption(String key, String name, String defValue) {
        super(key, name);
        this.defValue = defValue;

    }
    // return numSlots as 2
    @Override public int numSlots(){
        return 2;
    }
    /// getter for defValue
    public String getValue() {
        return this.defValue;
    }
    @Override public boolean match(String[] s, int i) {
        // Call in method from parents class using super()
        if (super.match(s,i)){
            this.defValue=s[i+1]; //if true, save next value
            return true;
        }
        else {return false;} // if false, return false
    }
    @Override public String toString() {
        // Override toString with new format
        return String.format("%s: %s", super.getName(), getValue());
    }
}

Add a comment
Know the answer?
Add Answer to:
**** ITS MULTI-PART QUESTION. PLEASE MAKE SURE TO ANSWER THEM ALL. SOLVE IT BY JAVA. ****...
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
  • Here is a sample run of the tester program: Make sure your program follows the Java...

    Here is a sample run of the tester program: Make sure your program follows the Java Coding Guidelines. Consider the following class: /** * A store superclass with a Name and Sales Tax Rate */ public class Store {      public final double SALES_TAX_RATE = 0.06;      private String name;           /**      * Constructor to create a new store      * @param newName      */      public Store(String newName)      {           name = newName;      }     ...

  • Use inheritance to create a new class AudioRecording based on Recording class that: it will retain...

    Use inheritance to create a new class AudioRecording based on Recording class that: it will retain all the members of the Recording class, it will have an additional field bitrate (non-integer numerical; it cannot be modified once set), its constructors (non-parametrized and parametrized) will set all the attributes / fields of this class (reuse code by utilizing superclass / parent class constructors): Non-parametrized constructor should set bitrate to zero, If arguments for the parametrized constructor are illegal or null, it...

  • In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program...

    In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program to create a database of dogs of your own. You will also include File I/O with this program. You will create 3 classes for this assignment. The first class: Create a Class representing the information that is associated with one item (one dog) of your database. Name this class Dog. Using Lab 3, this will include the information in regard to one dog. The...

  • java programming how would i modify the code below to add a GUI (with a main menu with graphics and buttons, etc...) and include an option to print a list of all students added in a grid format and sh...

    java programming how would i modify the code below to add a GUI (with a main menu with graphics and buttons, etc...) and include an option to print a list of all students added in a grid format and short by name, course, instructor, and location. ///main public static void main(String[] args) { Scanner in = new Scanner(System.in); ArrayList<Student>students = new ArrayList<>(); int choice; while(true) { displayMenu(); choice = in.nextInt(); switch(choice) { case 1: in.nextLine(); System.out.println("Enter Student Name"); String name...

  • UPDATE THE UNIVERSE PROGRAM: C. Research the size of each CelestialObject and its distance from the...

    UPDATE THE UNIVERSE PROGRAM: C. Research the size of each CelestialObject and its distance from the sun (for planets) and the distance of the moons from the planets D. Calculate the distance between any two CelestialObject (e.g. between 2 planets and between two moons) COMPLETE STEPS C AND D and THE MODIFICATION BELOW. SUBMIT THE UPDATES! 1. GALAXY CLASS //**MODIFICATION NEEDED** //Use the DBPM format to complete the class. //Review the SolarSystem class for the Star attribute as an example...

  • JAVA help Create a class Individual, which has: Instance variables for name and phone number of...

    JAVA help Create a class Individual, which has: Instance variables for name and phone number of individual. Add required constructors, accessor, mutator, toString() , and equals method. Use array to implement a simple phone book , by making an array of objects that stores the name and corresponding phone number. The program should allow searching in phone book for a record based on name, and displaying the record if the record is found. An appropriate message should be displayed if...

  • Java Programming Question

    After pillaging for a few weeks with our new cargo bay upgrade, we decide to branch out into a new sector of space to explore and hopefully find new targets. We travel to the next star system over, another low-security sector. After exploring the new star system for a few hours, we are hailed by a strange vessel. He sends us a message stating that he is a traveling merchant looking to purchase goods, and asks us if we would...

  • Read through the code of the class Player, noting it has two instance variables, name and rank, which are of type String and three further instance variables won, drew and lost which are of type int....

    Read through the code of the class Player, noting it has two instance variables, name and rank, which are of type String and three further instance variables won, drew and lost which are of type int. There is also an attribute of the class, points, which does not have a corresponding instance variable. Also note the constructor and methods of the class and what they do. TournamentAdmin class code: public class RankAdmin {    /**     * Constructor for objects of class...

  • please write code in java, assignment is due soon Thanks. public interface Named The Named interface...

    please write code in java, assignment is due soon Thanks. public interface Named The Named interface is a simple interface which applies to anything which has a name. The only thing required is the following method: String name() which returns the name of the instance. public interface MessageSink, It includes: void deliver(Named sender, String message) delivers the specified message from the given sender. public interface Sharable, which is Named, It includes no method. public abstract class GeneralCapability It incudes: The...

  • Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class...

    Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class Delete extends Info { String name; int Id; int del; public Delete() { } public void display() { Scanner key = new Scanner(System.in); System.out.println("Input Customer Name: "); name = key.nextLine(); System.out.println("Enter ID Number: "); Id = key.nextInt(); System.out.println("Would you like to Delete? Enter 1 for yes or 2 for no. "); del = key.nextInt(); if (del == 1) { int flag = 0; //learned...

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