Assignment Chef icon Assignment Chef

Browse assignments

Assignment catalog

33,401 assignments available

[SOLVED] Comp 3700: project 3—dragon game part 1

Goals: • To understand how important the to-do list before designing a use case diagram. • To figure out the logical structure in a use case diagram.1. Background A customer wants a cool new video game, similar in style to popular video games like World of Warcraft or Bioshock. However, the customer recognizes the lack of significant funds and only has a resource poor computer to play this game on. Hence, the game will be a simple text-based adventure concerning a graduate student trying to navigate his way down Shelby Center. In this project, you will help the customer to design and implement a simple text-based game. 2. Requirement Details 2.1. Player The “player” is represented by at least three attributes: intelligence, time, and money. If the player runs out of intelligence, time or money, the player dies. The goal of the player is to survive to the end of the “hall” with the highest combined total of the attributes as possible. “Score” is determined as the three attributes multiplied together. 2.2. The Hall The player starts the game at the beginning of a hall, which is linear. The “Hall” is a path that is at least twenty (20) steps long. After a move, the user should be told how far away from the goal they are (in steps). If the player survives to the goal square without any of the attributes falling to 0, they win. Their score should be displayed with a simple ASCII victory message. If the player dies, a “You Lose” message should appear indicating the cause of death (for example, if money falls to zero, you can say that the player starved to death because of poverty). All the attributes should start in some random range (e.g. 8-25). 2.3. Turns Every turn, the player has (at least) 5 options to choose from: • Move: The player moves one step in the grid, but risks an Encounter or a Puzzle. Moving also takes time. • Read technical papers (boost intelligence): The player loses a fixed amount of time, but increases intelligence by a random amount • Search for loose change (boost money): The player loses a fixed amount of time, but increases money by a random amount. • View character: A simple display should show the character attributes and current position in the hall (ASCII is fine) • Quit the game (shows the “You Lose” screen – optional mockery- and exits the program) Project 3 – page 3 2.4. Encounter Encounters: Every time the character steps, there is a random change of various events happening. You are free to change the probabilities as you see fit for “game balance,” but here are some suggestions: • 25% chance: nothing happens, you just move forward. • 30% chance: You encounter a Puzzle (see Puzzle below) • 10% chance: Encounter a professor. This loses a random extra amount of time, but may slightly increase intelligence. • 10% chance: Encounter another graduate student. This loses a random amount of time. • 15% chance: Attacked by grunt work! Lose both time and intelligence. • 10% chance: Grade papers. Lose time, but gain money. • 0% chance: Get a huge raise, gain lots of money! (This never happens). 2.5. Puzzles Puzzles: Puzzles are different from normal encounters since they require interaction from the user. These don’t necessarily have to be brilliant, but riddles or even edutainment light puzzles are fine. Examples: • “What is 2 + 2:” For a correct response, Money + 1. For an incorrect response, Money -20 (you idiot). • “What can you put in a barrel to make it lighter?” For a correct response, int+2. For an incorrect response, int-2. 2.6. Other options You are free to add more details and rules to your game, but you must have at least the above specifications. Feel free to be creative – there are many opportunities to do so. 3. No Late Submission • Late submissions will not be accepted and will result in ZERO without valid excuses, in which case you should talk to Dr. Li to explain your situation. • GTA/Instructor will NOT accept any late submission caused by Internet latency. 4. Rebuttal period • You will be given a period of two business days to read and respond to the comments and grades of your homework or project assignment. The TA may use this opportunity to address any concern and question you have. The TA also may ask for additional information from you regarding your homework or project. 5. Rubrics Project 3 – page 4 5.1 Based on the game description above, you need the following information to design a use case diagram (5 points each): 1. Project broken down into multiple small functionalities. 2. Identify the goal and priority. 3. Functionality Scope. 4. Identify relationship and association. 5. Identify Extension and Inclusion of use cases. 6. Identify Multiplicity 7. Naming Use Case and actors 8. Important note points 5.2 Documents (20 points each list) Also, please submit three lists in a single PDF file: a) List of Actors of the Project; b) List of Use Cases/Activities; and c) List of System (Functionality list). 5.3 Submission Please submit your project preparation work as a .pdf file Project3_ firstname_lastname.pdf Project 3 – page 5 Sample Usage What’s your name? Bob =========================================================== | Welcome, Bob! | =========================================================== 1) Start a New Game of Dunstan and Dragons! 2) View top 10 High Scores 3) Quit Please choose an option: 2 The top 5 High Scores are: Win 1337 CaseyZZZ 625 JonnieKill 400 Bob 75 Daisy 33 -no more scores to show1) Start a New Game of Dunstan and Dragons! 2) View top 10 High Scores 3) Quit Please choose an option: 1 Entering the Dungeon… You have: intelligence: 20 time: 25 money: $11.00 You are 20 steps from the goal. Time left: 25. 1) Move forward(takes time, could be risky…) 2) Read technical papers (boost intelligence, takes time) 3) Search for loose change (boost money, takes time) 4) View character 5) Quit the game Project 3 – page 6 Please choose an action: 4 You have: intelligence: 20 time: 25 money: $11.00 You are 20 steps from the goal. Time left: 25. 1) Move forward(takes time, could be risky…) 2) Read technical papers (boost intelligence, takes time) 3) Search for loose change (boost money, takes time) 4) View character 5) Quit the game Please choose an action: 2 You read through some technical papers. You gain 3 intelligence, but lose 2 units of time. You are 20 steps from the goal. Time left: 23. 1) Move forward (takes time, could be risky…) 2) Read technical papers (boost intelligence, takes time) 3) Search for loose change (boost money, takes time) 4) View character 5) Quit the game Please choose an action: 1 You move forward one step, and… NOTHING HAPPENS! You spent one unit of time. You are 19 steps from the goal. Time left: 22. 1) Move forward (takes time, could be risky…) 2) Read technical papers (boost intelligence, takes time) 3) Search for loose change (boost money, takes time) 4) View character 5) Quit the game Please choose an action: 1 You move forward one step, and… YOU FIND SOME PAPERS TO GRADE. Project 3 – page 7 You spent two units of time, but gained $3.00! You are 18 steps from the goal. Time left: 20. You can move forward or backward. 1) Move forward(takes time, could be risky…) 2) Read technical papers (boost intelligence, takes time) 3) Search for loose change (boost money, takes time) 4) View character 5) Quit the game Please choose an action: 1 You move forward one step, and… PUZZLE: It’s a riddling imp. I hate riddling imps. But fine, he asks: “Find the product of 8 and 8!” 1) 16 2) 64 3) 256 4) Uh…uh… no? Choose wisely: 4 The imp cackles “Oh yes. Yes indeed. Now you die.” TIME HAS FALLEN TO ZERO. YOU DIE.

$25.00 View

[SOLVED] Comp 3700: project 2 audisktool – a tool for monitoring disk devices

1. Building your Linux disk monitoring tool – auDiskTool In this project, you have a Linux tool called – auDiskTool – to monitor disk performance (i.e., I/O transfer rates) in a Linux system. Your auDiskTool can output a file containing a list of reports (attached at the end) that help system administrators in configuring the Linux system to achieve good disk I/O performance. The monitoring reports created and maintained by your auDiskTool offers statistical information on I/O transfer rates. Our long-term goal is building a tool to monitor both processor and disk performance of Linux systems. However, the short-term goal to be achieved in this project is to generate a state diagram. After you complete this project, you may extend your auDiskTool to monitor processor performance in addition to disk performance. 2. Requirements 2.1. Statistical Information Each report item recorded in an output file contains statistics on a per disk or partition basis. auDiskTool allows users to choose a particular disk or partition to monitor. If no disk nor partition is chosen by the users, then auDiskTool monitors all disks used by the Linux system. Each report item may show the following information: Device: This column provides the disk or partition name (e.g., sda). If your Linux machine has new kernels, the device name listed in the /dev directory is displayed. If your Linux kernel is 2.4, the format of the names is devm-n, where m is the major number of the device, and n is a distinctive number. If your Linux kernel is 2.2 (this is an uncommon case), the name will be displayed as hdiskn. Blk_read: This column reports the total number of reads. Blk_read/s: This column indicates the number of reads from the disk per second. KB_read/s: This column indicates the amount of data blocks read from the disk per second (i.e., measured in Kilobytes per second). Note: we assume the size of sector is 1 KB. Blk_wrtn: This column reports the total number of blocks written. KB_wrtn/s: This column indicates the number of data blocks written to the disk per second. (i.e., measured in Kilobytes per second.) Blk_wrtn/s: This column indicates the number of data blocks written to the disk per second. 2.2. Configure Time Interval and Count Your auDiskTool can set an interval parameter, which specifies the amount of time measured in seconds between two consecutive disk reports. Each disk report contains statistics collected during the interval since the previous report is recorded. Your auDiskTool also can decide the number of reports to be collected in an output file. If the interval parameter and the count parameter are not specified, auDiskTool may use default values. For example, the default value of the interval parameters is 1 second; the default value of the count parameter is 10. 2.3. Specify the File Name of an Output Report Your auDiskTool should allow users to specify the file name of an output report. The file name may be fully specified with a path. If no path is provided, then the working directory will be the current directory where the new report file is created. If the output file exists, then new report items will be appended at the end of the existing file. Note 1: If users specify a file name that does exist, auDiskTool must inform users that an output report file with the same name exists and reported items will be added to the existing file. Note 2: If the report file name is not specified, then “report.adt” will be used as a default output file name. 2.4. Specify what statistical data to be reported In section 3.1, we list 7 statistical data items. Your tool should allow users to decide what data items to be included in a report. A configuration file (see Section 3.5 blow) stores default values for these decisions. 2.5. A Configuration File – audisktool.conf All the default parameters (e.g., time interval, count, output file name) are stored in a configuration file. This configuration file is loaded into main memory when auDiskTool starts its execution. The configuration file name is “audisktool.conf”. The format of the configuration file is: Interval, count, print_blk_read, print_blk_read/s, print_kb_read/s, print_blk_write, print_blk_write/s, print_kb_write/s The values of print_blk_read, print_blk_read/s, print_kb_read/s, print_blk_write, print_blk_write/s, print_kb_write/s can be either ‘1’ or ’0’. ‘1’ means that the value will be reported; ‘0’ means the value is ignored in the report. For example, suppose we have the following configuration file: 5 10 1 1 1 0 0 0 The above file indicates that Interval is 5 seconds, count is 10, report values of blk_read, blk_read/s, kb_read/s and do not include the values of blk_write, blk_write/s, kb_write/s in the report. You do not need to submit this configuration file via Canvas; the TA will use the configuration file with the following parameters to test your implementation: 1 10 1 1 1 1 1 1 2.6. Display the report Users are allowed to open the report and display monitoring records inside audisktool. If the report file does not exist or cannot be opened, audisktool must show a warning message. 2.7. System Quit This should safely terminate the audiskTool. If any parameter (e.g., time interval and count) is updated, the system parameters must be saved back to the configuration file called “audisktool.conf”. 3. Retrieve Disk Statistics The Linux (version 2.4.20 and above) operating system offers extensive disk statistics to measure disk activities. You can use the following command to check the version of your Linux: $uname -r Linux Version 2.6 and above: The disk statistical information can be found in /proc/diskstats You can use the following command to display this file: $cat /proc/diskstats Example 1: Below is an example to show the format of the above file: 3 0 sda 446216 784926 9550688 4382310 424847 312726 5922052 19310380 0 3376340 23705160 3 1 sda1 2 0 4 24 0 0 0 0 0 24 24 You also can use the following command to display the information related to disks in the /proc/diskstats file. $grep ‘sda’ /proc/diskstats Note that grep is a utility program for searching plain-text data sets for lines matching a regular expression (e.g., ‘sda’ in our case). 4. Format of “/proc/diskstats” In example 1 shown on page 4, you can find each row has 14 items. The first three items are the major and minor device numbers, and device name. For example, given the following row: 3 1 sda1 2 0 4 24 0 0 0 0 0 24 24 The major device number is 3, and minor device number is 1, and device name is sda1. The 11 fields listed after the device name are statistics data of the device whose major/minor device numbers as well as name are shown in the first three fields. All these 11 fields except field 9 are cumulative since boot. Note that field 9 goes to zero as I/Os complete; all others only increase. These fields are unsigned long numbers. The 11 fields are explained below: Field 1: # of reads completed. This is the total number of reads completed successfully. Field 2/6: # of reads/writes merged. Reads and writes which are adjacent to each other may be merged for efficiency. Thus two 4K reads may become one 8K read before it is ultimately handed to the disk, and so it will be counted (and queued) as only one I/O. This field lets you know how often this was done. Field 3: # of sectors read. This is the total number of sectors read successfully. Field 4: # of milliseconds spent reading. This is the total number of milliseconds spent by all reads (as measured from make_request() to end_that_request_last()). Field 5: # of writes completed. This is the total number of writes completed successfully. Field 7: # of sectors written. This is the total number of sectors written successfully. Field 8: # of milliseconds spent writing. This is the total number of milliseconds spent by all writes (as measured from make_request() to end_that_request_last()). Field 9: # of I/Os currently in progress. The only field that should go to zero. Incremented as requests are given to appropriate struct request_queue and decremented as they finish. Field 10: # of milliseconds spent doing I/Os. This field increases so long as field 9 is nonzero. Field 11: weighted # of milliseconds spent doing I/Os. This field is incremented at each I/O start, I/O completion, I/O merge, or read of these stats by the number of I/Os in progress (field 9) times the number of milliseconds spent doing I/O since the last update of this field. This can provide an easy measure of both I/O completion time and the backlog that may be accumulating. 5. Rubrics: 1. Please list class names. (18 points) 2. Use argoUML to create a state chart diagram. (10 points) 3. For each class, please add proper info – at least one attribute and operation. If no ops, please indicate N/A– for software engineers to define them. (16 points) 4. Please indicate the relationship among classes with proper types of lines. (20 points) 5. Please indicate the conditions for transitions. (16 points) 6. Please specify the multiplicity. (15 points) 7. Submit your solution on Canvas with the format: project2_firstname.zargo. (5 points) 6. No Late Submission • Late submissions will not be accepted and will result in a ZERO without valid excuses, in which case you should talk to Dr. Li to explain your situation. • GTA/Instructor will NOT accept any late submission caused by Internet latency. 7. Rebuttal period • You will be given a period of two business days to read and respond to the comments and grades of your homework or project assignment. The TA may use this opportunity to address any concern and question you have. The TA also may ask for additional information from you regarding your homework or project. Sample Usage 1. Help $./audisktool_aak0010 help run – run the monitoring tool. set interval [value] – set sampling period to [value] set count [value] – set the number of records to [value] set report [name] – set report file name to [name] set blk_read [0|1] – set print_blk_read to 0 or 1 set blk_read/s [0|1] – set print_blk_read/s to 0 or 1 set kb_read/s [0|1] – set print_kb_read/s to 0 or 1 set blk_write [0|1] – set print_blk_write to 0 or 1 set blk_write/s [0|1] – set print_blk_write/s to 0 or 1 set kb_write [0|1] – set print_kb_write to 0 or 1 print conf – display all the parameters print report – open and display the report file save – the configuration file audisktool.conf is updated display – exit – exit the tool. > 2. Run the tool $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >run Monitoring time = 5 Seconds, Number of records = 10, print_blk_read = 1, print_blk_read/s = 1, print_kb_read/s = 1, print_blk_write = 0, print_blk_write/s = 0, print_kb_write/s = 0, report file name = ‘report.adt’ Please wait … A file “report.adt” is updated. > 3. Change report file name $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >set report aak0010.adt The report file name is changed from ‘report.adt’ to ‘aak0010.adt’. You can now type ‘run’ to generate new records to be saved in ‘aak0010.adt’. Note: ‘report.adt’ will not be deleted by audisktool. > 4. Display records in the report file 4.1 no record is found $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >print report No record found in ‘report.adt’ > 4.2 Records are found $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >print report 2 records found in ‘report.adt’ blk_read blk_read/s kb_read/s blk_write blk_write/s kb_write/s 10 1.13 2.26 N/A N/A N/A 55 > 5.4 10.8 N/A N/A N/A 5. Change count and interval $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >set count 15 The number of records generated in each run has been changed to 15. >set interval 3 The sampling interval has been changed to 3 seconds. > 6. Change print_blk_read and other similar parameters $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >set blk_read 0 Print_blk_read has been changed to 0. >set blk_write 0 Print_blk_write was 0; the parameter remains unchanged to 0. > 7. Display all the parameters. $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >print conf Monitoring time = 5 Seconds, Number of records = 10, print_blk_read = 1, print_blk_read/s = 1, print_kb_read/s = 1, print_blk_write = 0, print_blk_write/s = 0, print_kb_write/s = 0, report file name = ‘report.adt’ > 8. Save the configuration file 8.1 no need to save $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >save audisktool.conf has not been updated. There is no need to save the file. 8.2 change can save the configuration file $./audisktool_aak0010 auDiskTool, version 1.0.0. Type ‘help’ to find more about commands. >set blk_read 0 Print_blk_read has been changed to 0. >save file audisktool.conf has been updated. >

$25.00 View

[SOLVED] Comp 3700: project 1

There are several “categories” if students plan to borrow books from our library. For example, Li would like to improve teaching skills, therefore learning skills from the history is the best solution to guide Li in the future. Surprisingly, a textbook “Aviation Instructor’s Handbook” is saved in the library. Li needs several steps to “grab” this book. For example, type the textbook name on AU library website to see where it is i.e. which collection area, which floor, which shelf (alphabetically). Unfortunately, currently the library app and website are under maintenance. They are not open to users until a clear class diagram is presented by software developers. What can you do to accelerate it? Based on the description above, please draw a class diagram via argoUML and submit .zargo file in Canvas. Notes: As a designer, think about 1) what info users need; 2)how software provides info; 3)from perspective of software design, what additional info you need i.e. what if users don’t return books on time. In your class diagram, not only provide all necessary class boxes, but also indicate relationships. Rubrics: 1.Please list class names. (18 points) 2.For each class, please add proper info – at least one attribute and operation. If no ops, please indicate N/A– for software engineers to define Project 1 – page 2 them. (37 points) 3.Please indicate the relationship among classes with proper types of lines. (20 points) 4.Please specify the multiplicity. (20 points) 5. Submit your solution on Canvas with the format: project1_firstname.zargo. (5 points) NO Late Submission: • Late submissions will not be accepted and will result in a ZERO without valid excuses, in which case you should talk to Dr. Li to explain your situation. • GTA/Instructor will NOT accept any late submission caused by Internet latency. Rebuttal period: • You will be given a period of two business days to read and respond to the comments and grades of your homework or project assignment. The TA may use this opportunity to address any concern and question you have. The TA also may ask for additional information from you regarding your projects.

$25.00 View

[SOLVED] Comp3220 ada programming assignment

For this programming assignment, you will be writing an ada program that primarily works with binary arrays. A binary array is simply an array that is of length 16 that can ONLY hold 1’s and 0’s. You will need to implement the following procedures and functions (recall that procedures ONLY work with parameters and don’t return anything, while functions return data), whose prototypes have been provided to you in the assgn.ads package (this file is kind of like a header file in c, you will need to define these protocols in assgn.adb). 1) Procedure Init_Array. Accepts a two-way parameter (in-out mode) that is a BINARY_ARRAY and fills it with an initial set of random values. I have provided a second package to you, as a convenience, that you can use to generate random values with. Keep in mind as you generate this binary array that generating a binary value too large could result in an overflow when attempting to add two binary arrays together. 2) Procedure Print_Bin_Array. This procedure accepts a BINARY_ARRAY (in-mode only) and simply prints it to the console. 3) Procedure Reverse_Bin_Arr. This procedure accepts a BINARY_ARRAY (in-out mode) parameter and simply reverses that BINARY_ARRAY. 4) Function Int_To_Bin. This function accepts an INTEGER value (in-mode only) and returns the equivalent BINARY_ARRAY 5) Function Bin_To_Int. This function accepts a BINARY_ARRAY value (in-mode only) and returns the equivalent INTEGER. Overloaded functions: When doing addition or subtraction for the overloaded operators below, you MUST perform BINARY addition or subtraction (adding or subtracting 1’s and 0’s one position at a time, and carrying, if necessary. Do NOT simply convert to integer values and add or subtract integers. 6) Overloaded “+” operator that accepts an INTEGER type and a BINARY_ARRAY type (in-mode only), adds them together and returns a BINARY_ARRAY that is the result. Ada Programming Assignment 7) A second Overloaded “+” operator that accepts two BINARY_ARRAY types (inmode only), adds them together and returns the result as a BINARY_ARRAY 8) Two Overloaded “–“ operators that behave like #6 and #7 above. I’ve provided you with a main.adb file (an ada file with a main method in it) that you can use to test your code. Helpful Links: For linux systems you can simply install gnat-X, where X is some version number, to get all of the tools you need to compile and link ada programs. Download here. You want GNAT ada 2016: http://libre.adacore.com/download/ Old but very useful (careful with the chapter on packages. Newer versions of ada require you to write them in two separate files. The specification belongs in .ads, and the implementation belongs in .adb): http://perso.telecom-paristech.fr/~pautet/Ada95/intro.htm Other Useful Links: http://www.cs.fsu.edu/~baker/ada/examples/ http://www.cristhianny.com/others/ada_tutorial_introduction_code.html http://www.adapower.com/adapower1/articles/class.html

$25.00 View

[SOLVED] Comp3220 racket interpreter

For this part of the homework assignment, we will be creating an interpreter for our TINY programming language in scheme. Our program should be able to take an AST (created by our parser) written in a list format, and “execute” those instructions in racket. Details I have given you a mostly completed racket file that you will need to complete to finish the interpreter. Our program defines an “interpreter” that accepts a “program” (an AST from the previous homework assignment that has been formatted as a list) and executes it. Note that the format of the AST does NOT include the token names (as they did in the assignment). Should you wish to modify your program so that yours produces the same output, you could then use this to produce more test cases than the ones that I will provide to you. You simply need to modify the toStringList method. I have included several “programs” at the bottom that you can give your interpreter to execute without having to run your previous assignment to generate programs. Referencing Environment The reference environment for our TINY language is every variable we’ve seen the entire time our program has been running. We can’t use a variable until it has been created and assigned a value. When we start our interpreter, one of the first things it will do is create an empty reference environment. It should pass this environment along with a single “statement” (recall we built our AST tree so that a program is a series of statements, where each statement is another child of program). Each time our interpreter encounters an assignment statement, it should add the new variable (and it’s value) to the reference environment. Each time a statement is processed, the interpreter should decide whether it’s looking at a variable, and if it is, it should search for the value of that variable in the reference environment (that it was passed). I have provided several of the functions for you: • empty-env: creates an “empty reference environment” • extend-env: accepts a reference environment, a variable, and it’s value and adds the variable and it’s value to the reference environment • apply-env: accepts a reference environment and a variable and returns its value (or an error message if it cannot find that variable in the reference environment) Extra Credit (5 Points) Add the ability for your interpreter to handle at least the following Boolean expressions: , and Hint: in scheme the symbols for the boolean operators above are what is written above (, and) Racket Interpreter (15 Points) Add the ability for your interpreter to handle while loops. Grading: (20 points each) 5 test programs similar to [a-e]prog Some will have errors. (5 points extra credit) 1 test program to see if your interpreter can handle the following boolean operators: >,

$25.00 View

[SOLVED] Comp3220 ruby parser 2: build ast tree

For this part of the Ruby Interpreter Collection of Assignments we will be modifying our existing Parser so that instead of printing parser output, it will build an AST (abstract syntax tree) that our interpreter can use to “run” programs written in the Tiny Language. Details I have given you all the files necessary to complete the assignment. You will need to modify Parser.rb so that it builds the AST while it is parsing a file. I have included an AST.rb file that defines an AST node object that can be used to build this tree. It also has a method that can print the tree in list format (convenient since our interpreter will be written in a list-based language!). You should NOT modify AST.rb unless you are attempting the extra credit (see Extra Credit section below). I have done some of the work for you in Parser, so that you can use that as an example of how you should proceed. At the end of this document are screenshots showing what correct output should look like given some input files that I will also provide to you for debugging. Note: We are building an AST and NOT a parse tree. What is the difference anyway!? The difference is that a Parse Tree parse tree would look much like the examples we went through in class when we compared parse trees to derivations. They would INCLUDE every rule in our class as root nodes or sub nodes in the tree. However, an AST (Abstract Syntax Tree) AST ONLY includes the actual lexemes that are needed to be interpreted. If you take a look at the compiler series article here: https://ruslanspivak.com/lsbasi-part1/ , they illustrate that in one of the series articles. Here is the specific article in the series that introduces AST’s: https://ruslanspivak.com/lsbasi-part7/ . For our assignment, we will always start with a program node as the root of the whole tree. That is the only “not concrete” thing that should be part of our tree. Extra Credit (25 pts) – must score 100 to qualify for any extra credit points. Otherwise, you only get 20 pts per test case passed. Part 1 (5 pts) Because of the way our grammar is defined (and because we want to produce a tree in list format) our tree WILL be nested correctly BUT our operands will be in reverse order. Since it is something that is consistent, it is an easy problem to handle in our interpreter (we already know it will behave this way, so just read in the operands in reverse order). However, it is possible to produce the tree in list form with the operands in correct order. In order to do this, you will need to modify the AST.rb class. One way to do this is to: 1) add a method in AST.rb that allows you to swap the first child of a node 2) instead of calling addChild everywhere in Parser.rb, there are at least 2 instances where you will need to call your new custom function instead (maybe called addAsFirstChild). Part 2 (20 pts) This potential issue is a bit harder to fix (and describe) and requires that you (1) have a really good understanding of exactly how this AST tree works and (2) how our interpreter is going to process our tree (specifically that any math Ruby Parser 2: Build AST tree operator (except for equal) requires at least 2 operands). So, (- 3 4) is ok, but (- 4) is not. Scheme can actually handle this, but our interpreter won’t be able to. See examples below. To get a really good understanding of how our AST tree is being built, I would recommend studying the toStringList() method in AST.rb to understand how its going through the tree in order to print things. You could then create a second toStringList() in AST.rb that is a modification of the first one. You could attempt to create this second one so that instead of printing the Token AND the Lexeme, it ONLY prints the lexeme. This will actually end up giving you something you can copy and paste into scheme to verify if it’s computing the answer correctly. Example of the problem: 1 – 2 – 3 – 4 is -8. You can type that into a calculator and get the correct result. However, you can’t type that into scheme (the way it is written) and get a correct result. Since scheme is a list-based language, it expects that the first item in the list be the operator. If you don’t attempt the first part of the extra credit (5 pts), this is what your parser will produce. You can get this string exactly, by simply removing the Token names (or by writing a second toStringList() method that will print lexemes only). In this example, we are not reversing first operand (we can handle this in Interpreter). You can paste the partial tree below into scheme and it will produce a result, however, our interpreter will not be able to process it because there is an operator with just a single operand in this list; the inner ( – 4 ). ( – 2 ( – 3 ( – 4 ) ) 1 )  scheme will give you -6 as a result, which is still incorrect, even though it runs If you do attempt the first part of the extra credit (5 pts), this is what your parser will produce. Note that we STILL have that inner list ( – 4 ) where the minus operator has only a single operand, the 4. Although you could type this expression into scheme and it would give you a correct result, our interpreter will still crash because of the the inner list ( – 4 ). ( – 1 2 ( – 3 ( – 4 ) ) ) Below is what you get 20 points for! In addition to swapping the first child of some nodes (part 1) you will also occasionally need to “reverse” an entire subtree. You can think about this as if you were “flipping” a sub-tree over, where the bottom (the leaf/leaves) become the new root and the top (the root) becomes the new leaf/leaves. Doing this would produce a tree that scheme could use to correctly calculate a result AND our interpreter will ALSO be able to use the tree to produce the correct output. Continuing the example above, this method would produce the following list that would be correct for our interpreter. ( – ( – ( – 1 2 ) 3 ) 4 )  I’ll go over this in class Ruby Parser 2: Build AST tree Screenshots No extra credit input1.tiny (20 pts) input2.tiny (20 pts) input3.tiny (20 pts) input4.tiny (this one has syntax errors) (20 pts) input5.tiny (this one has syntax errors) (20 pts) Ruby Parser 2: Build AST tree Extra credit (5 pts only) – MUST score 100 to get the +5 points, otherwise you simply get 20 pts for each test passed. input1.tiny (20 pts) input2.tiny (20 pts) input3.tiny (20 pts) input4.tiny (this one has syntax errors) (20 pts) input5.tiny (this one has syntax errors) (20 pts) Ruby Parser 2: Build AST tree Extra credit (20 pts) – MUST score 100 AND get 5 pts extra credit to qualify for these points. MUST pass BOTH test cases below to earn the additional 20 points. input6.tiny input7.tiny

$25.00 View

[SOLVED] Comp3220 ruby parser part 1

For this assignment, we will be writing a parser that is able to parse an input file written in our “Tiny” grammar. You should finish writing the “Parser” class that I’ve provided. Your Parser class should print: • Each time it enters or leaves a rule and what the rule is: Entering [RULE_NAME] Rule Exiting [RULE_NAME] Rule There are two exceptions: the ID and the INT rules. In this grammar, ID and INT are also Token names, so we will not print when we are “entering” or “exiting” those rules since we can just check the token type. • Each time it recognizes a token and what the token was: Found [TOKEN_TYPE] Token: [LEXEME] For rules with Epsilon definitions, you should also indicate if that definition was chosen: Did not find [TOKEN_TYPE] or [TOKEN_TYPE] Token, choosing EPSILON production • Something, everytime it catches an error: Expected [TOKEN_TYPE] found [LEXEME] When the error could have been multiple things, separate the token types with the word or Expected [TOKEN_TYPE] or [TOKEN_TYPE] or [TOKEN_TYPE] found [LEXEME] • How many parse errors were found There were [X] parse errors found. Parser.rb extends Lexer.rb (The lexer that you wrote for your last assignment) and provides a framework for a topdown, recursive-descent parser of the TINY language. The parser stays one token ahead in the Token stream (@lookahead) and uses the Token to predict how to continue parsing the current instruction and which method to call next. The consume() method calls nextToken() in the scanner. The current @lookahead Token is discarded, and the next Token in the stream is retrieved. Whitespace Tokens are discarded. The match(dtype) method tries to match the @lookahead Token with the provided type (dtype). If a match is found, consume() is called to retrieve the next Token. Otherwise an error message is displayed and then consume() is called to retrieve the next token. The program() method is first called to parse a TINY program. Since a TINY program consists of a sequence of statements, program() calls statement() repeatedly until it encounters the EOF token. Complete the parser by providing methods for the appropriate BNF rules in TINY. I have given you my lexer and token ruby classes. I have also partially written the parser for you and have written a main.rb file that can run your ruby parser. Your assignment is to FINISH WRITING THE PARSER (parser.rb). I have also included 5 sample input files that you can use to test your program once you’ve finished writing it. input[1-3].txt should complete with no parse errors. input[4-5].txt should have parse errors. Below are screenshots of what your output should look like for the original (not extra credit) grammar, based on the input files I’ve provided. Extra Credit The extra credit is to implement the Boolean version of the grammar. I will run 5 tests against your code. If you implemented the Boolean version of the parser, each test will be worth 24 points instead of 20 points (still 5 tests). You can test your code by using input6-8.tiny that are provided in vocareum. Ruby Parser Part 1 input3.txt Ruby Parser Part 1 input4.txt Ruby Parser Part 1 input5.txt

$25.00 View

[SOLVED] Comp2210 word ladders

The focus of the assignment is to implement a word connection game that has been played in one variation or another for almost 150 years. The object of the game is to transform a start word into an end word of the same length by a sequence of steps, each of which consists of a one-letter change to the current word that results in another legal word. Charles Lutwidge Dodsgon (Lewis Carroll) invented this game and called it “Doublets.” It’s now more commonly known as Word Ladders. Consider the following examples. cat, can, con, cog, dog cat, bat, eat, fat, gat, hat clash, flash, flask, flack, flock, clock, crock, crook, croon, crown, clown Each is a valid word ladder from the start word to the end word since the start and end words are the same length and each word in between is exactly one letter different from the previous word. The game is usually played so that each player tries to find the shortest word ladder between two words. The shortest ladder would, of course, depend on the lexicon, or list of words, being used for the game. Using the SOWPODS word list (see below), word ladders with minimum length for the start-end pairs above would be: cat, cot, dot, dog cat, hat clash, class, claws, clows, clown Implementation Details You must implement your solution to the assignment in terms of WordLadderGame, an interface that specifies all the behavior needed to calculate word ladders, and Doublets, the shell of a class that implements the WordLadderGame interface. You must provide a correct implementation of the Doublets class by completing its constructor and providing a correct implementation of each method. You must not change the WordLadderGame interface in any way. You must meet all the requirements specified and implied by the Javadoc comments in these files. You may add as many methods as you would like, and you may add as many nested classes as you would like. Although you may import other classes that are part of the JDK, the imports already provided are the suggested ones that you will need. Downloads You can download the necessary starter code and resources here: ● WordLadderGame.java ● Doublets.java ● ExampleClient.java ● WordLists.jar The ExampleClient class illustrates basic calls to the WordLadderGame methods, and it also demonstrates how to associate a text file contained in WordList.jar with an InputStream object. Text files containing different word lists of various sizes are provided in the Java JAR file WordLists.jar. JAR files can be opened by most common file compression and archiving utilities, as well as jGRASP via the Project menu. You can also extract the contents of a JAR file on the command line by issuing the following command: jar xf WordLists.jar Acknowledgements Word search games of various sorts are popular CS 2 assignments because they bring together several important topics all in one place. This version of the word search problem owes thanks to Owen Astrachan and others.

$25.00 View

[SOLVED] Comp2210 word search game

In this assignment, you will implement a version of a word search game much like Boggle and other similar word games. The approach you take to finding words on the board will be a direct application of depth-first search with backtracking. The version of the game that you will implement is played on a square board according to the following rules. 1. Each position on the board contains one or more uppercase letters. 2. Words are formed by joining the contents of adjacent positions on the board. 3. Positions may be joined horizontally, vertically, or diagonally, and the board does not wrap around. 4. No position on the board may be used more than once within any one word. 5. A specified minimum word length (number of letters) is required for all valid words. 6. A specified lexicon is used to define the set of all valid words. Below, from left to right, is a sample 4×4 board with single letters in each position, a sequence of positions forming the word PEACE, and the list of all words with a minimum length of 5 found on the board using the words in the standard Unix /usr/share/dict/words file as the lexicon. A string is said to be on the board if it can be constructed according to rules 1 through 4. A string is said to be a valid word if it is contained in the specified lexicon (rule 6). A scorable word is a valid word of at least the specified minimum length (rule 5) that is on the board. HNTQ is on the board, but is not a valid word. PLACE, POPE, and PALE are valid words, but are not on the board. PEACE is a scorable word for any minimum length between 1 and 5. BOY is a valid word and it is on the board, but it would not be a scorable word if the specified minimum length is 4 or greater. The score for a scorable word is calculated as follows: one point for the minimum number of characters, and one point for each character beyond the minimum number. Thus, each scorable word of length K > M is worth 1 + (K – M) points, where M is the specified minimum length. For example, the scorable words of length five or more on the board above would earn a score of 31. (22 words of length 5, 3 words of length 6, and 1 word of length 7 give 22 + 6 + 3 = 31 points.) Implementation Details You must implement your solution to the assignment in terms of two provided files: WordSearchGame.java and WordSearchGameFactory.java, plus one class that you create from scratch all on your own. The interface WordSearchGame describes all the behavior that is necessary to play the game. So, we can think of this interface as the specification for a game engine. You must develop your own game engine that meets this specification. That is, you must write a class that implements the WordSearchGame interface. You can name this class anything you want and you can add as many additional methods as you like. The WordSearchGameFactory is a class with a single factory method for creating game engines. You must modify the createGame method to return an instance of your class that implements the WordSearchGame interface. Factory classes like this are convenient ways of completely separating an implementation (your class) from a specification (the provided interface). For example, the test suite used for grading has been written completely in terms of the interface and without any knowledge of the specific classes used in your implementation. A brief example client along with the corresponding output are given below. Although the class that implements the WordSearchGame interface must be in the same directory, the ExampleGameClient code is independent of its name or any other details of the class. public class ExampleGameClient { public static void main(String[] args) { WordSearchGame game = WordSearchGameFactory.createGame(); game.loadLexicon(“wordfiles/words.txt”); game.setBoard(new String[]{“E”, “E”, “C”, “A”, “A”, “L”, “E”, “P”, “H”, “N”, “B”, “O”, “Q”, “T”, “T”, “Y”}); System.out.print(“LENT is on the board at the following positions: “); System.out.println(game.isOnBoard(“LENT”)); System.out.print(“POPE is not on the board: “); System.out.println(game.isOnBoard(“POPE”)); System.out.println(“All words of length 6 or more: “); System.out.println(game.getAllScorableWords(6)); } } Corresponding output: LENT is on the board at the following positions: [5, 6, 9, 14] POPE is not on the board: [] All words of length 6 or more: [ALEPOT, BENTHAL, PELEAN, TOECAP] Methods related to the lexicon The three methods in the WordSearchGame interface that relate to loading and searching the lexicon are loadLexicon, isValidWord, and isValidPrefix. While loadLexicon is called only once per game, isValidWord and isValidPrefix will be called heavily throughout game play. These two methods must be efficient if the game is to run with reasonable response times when using large lexicons. The choice of collection or data structure to store the lexicon will determine just how efficient these methods can be. You have two basic choices to represent the lexicon: use a prebuilt collection from the JCF or implement your own custom data structure or collection. If you choose the former option, TreeSet will offer very good performance and provide very convenient methods. If you choose the latter option, a trie will provide even better (time) performance and will be a fun challenge to implement. The choice is completely up to you. A good (and optional) idea would be to develop your solution with a TreeSet to store the lexicon and then, if you have plenty of time at the end, make an attempt at building your own trie (or similar custom data structure). The loadLexicon method reads a list of words from a text file and stores each unique word in the data structure or collection that you select to represent the lexicon. You will notice that many of the words in the provided lexicon files are in lowercase while the game board is in uppercase. Be sure that the lexicon is loaded and all string comparisons are made in a case-insensitive manner. You will also notice that the provided lexicon files have different content and formats. Using a simple scanner, however, it is possible to use the same code to read in all the provided lexicon files. Note that the lexicon must be loaded before calling many of the other WordSearchGame methods. If any method that is dependent on a lexicon is called before loadLexicon, your code must throw an IllegalStateException. See the source code documentation for details. The isValidWord method searches the data structure that holds the lexicon for a specified string and indicates whether or not that string is present. If the string is present then it is a valid word. If the string is not present then it is not a valid word. The isValidPrefix method searches the data structure that holds the lexicon to determine if any word in the lexicon begins with the specified string. For the purposes of this method, a string should be considered a prefix of itself. For example, “cat” is a prefix of “cat” as it is of “catalog”. Methods related to the board The setBoard method accepts an array of length N^2 that specifies the content of each position on the NxN board. The elements of the array are the Strings on the board listed in row-major order. Thus, the elements in the array from index 0 to N^2 – 1 correspond to the positions on the board from left to right, top to bottom. The element at index 0 stores the contents of the board position (0, 0) – the upper left corner – and the element at index N^2 – 1 stores the contents of the board position (N-1, N-1) – the bottom right corner. In general, the String at index row * N + col is the content of board position (row, col). For example, the array a = [“E”, “E”, “C”, “A”, “A”, “L”, “E”, “P”, “H”, “N”, “B”, “O”, “Q”, “T”, “T”, “Y”] would correspond to the board show below on the left. The same board is shown below on the right but with each element annotated with its row-major position. Note that the letter N is at board position (2, 1), which corresponds to row-major position 2 * 4 + 1 = 9. The primary responsibility of the setBoard method is to populate the data structure that you choose to represent the board with the contents of the provided array of Strings. Once again, the choice of data structure to represent the board should be made in support of the algorithms that will depend on it (see game play methods below). Two obvious data structure choices include (a) just keeping the one-dimensional array of strings as the board representation or (b) creating a two-dimensional array of strings to directly represent the two-dimensional board being modeled. Other choices are possible, and the one you pick is at your discretion. The implementing class of the WordSearchGame interface must have a default board. Specifically, the above board should be set as the default so that it is available for game play even if the setBoard method has not been called. The getBoard method returns a string representation of the current board suitable for printing to standard out (i.e., as an argument to System.out.println). There is no particular format required. Choose the format that is most helpful to you. This method will not be tested or graded. Methods related to game play The methods that implement game play options are getAllScorableWords, isOnBoard, and getScoreForWords. The getAllScorableWords method returns a SortedSet of strings containing all scorable words on the board that are of a specified minimum length and can be constructed according to the game rules. If no words can be found, this method returns an empty SortedSet. The isOnBoard method takes a string parameter and determines whether or not that string is on the board as defined above. If the string is on the board, this method returns a List of Integers representing the row-major positions of each substring. (Remember: the board positions are filled with strings, not necessarily just single characters). For example, isOnBoard(“PEACE”) would return the list [7, 6, 3, 2, 1]. If the string is not on the board, this method returns an empty list. For example, isOnBoard(“PALE”) would return an empty list. Both getAllScorableWords and isOnBoard can be implemented using slightly different versions of depth-first search. The specific depth-first algorithms that you implement must be efficient enough for use on large game boards with large lexicons. The getScoreForWords method returns the cumulative score of all the scorable words in the given SortedSet. Provided word list files You have been provided with several word list files for creating lexicons. ● CSW12.txt: 270,163 unique words, used in international Scrabble tournaments ● OWL.txt: 167,964 unique words, used in North American Scrabble tournaments ● words.txt: 234,371 unique words, provided with Unix distributions ● words_medium.txt: 172,823 unique words, subset of the Unix list ● words_small.txt: 19,912 unique words, small subset of the Unix list Your solution should run efficiently with each of these files used for the lexicon. Acknowledgements Word search games of various sorts are popular CS 2 assignments because they bring together several important topics all in one place. This version of the word search problem owes thanks to (at least): Julie Zelenski, Owen Astrachan, and Mike Smith.

$25.00 View

[SOLVED] Comp2210 implementing collections – linkedset

This assignment requires you to implement a set collection using a doubly-linked list as the underlying data structure. You are provided with the Set interface and a shell of the LinkedSet implementing class. You must not change anything in the Set interface, but you must create correct implementations of the methods in the LinkedSet class. In doing so you are allowed to add any number of private methods and nested classes that you need, but you may not create or use any other top-level class and you may not create any public method. You must also use without modification the existing fields of the LinkedSet class. The Set interface is generic and makes no restrictions on the type that it can contain. The LinkedSet class is also generic, but it does make a restriction on the type variable: Any type bound by a client to T must be a class that implements the Comparable interface for that type. Thus, there is a natural order on the values stored in an LinkedSet, but not (necessarily) on those stored in another class that implements the Set interface. This is an important distinction, so pause here long enough to make sure you understand this point. The following sections describe each method to be implemented, organized according to the methods appearing in the Set interface and those specific to the LinkedSet class. Each method’s behavior is described below and in comments in the provided source code. You must read both. Note that in addition to correctness, your code must meet the stated performance requirements. General Collection Methods of the Set Interface These methods correspond to the general methods that would be supported by most any type of collection, but some have behavior specific to a set. add(T element) The add method ensures that this set contains the specified element. Neither duplicates nor null values are allowed. The method returns true if this set was modified (i.e., the element was added) and false otherwise. Note that the constraint on the generic type parameter T of the LinkedSet class ensures that there is a natural order on the values stored in an LinkedSet. You must maintain the internal doubly-linked list in ascending natural order at all times. The time complexity of the add method must be O(N), where N is the number of elements in the set. Note that one element being a duplicate of another means that the two elements are equal. Since duplicates are not allowed to be added to any implementing class of the Set interface, this is an example of why it’s important for the equals method and the compareTo method of a class to be consistent. remove(T element) The remove method ensures that this set does not contain the specified element. The method returns true if this set was modified (i.e., an existing element was removed) and false otherwise. The remove method must maintain the ascending natural order of the doubly-linked list. The time complexity of the remove method must be O(N), where N is the number of elements in the set. contains(T element) The contains method searches for the specified element in this set, returning true if the element is in this set and false otherwise. The time complexity of the contains method must be O(N), where N is the number of elements in the set. size() The size method returns the number of elements in this set. This method is provided for you and must not be changed. The time complexity of the size method is O(1). isEmpty() The isEmpty method returns true if there are no elements in this set and false otherwise. This method is provided for you and must not be changed. The time complexity of the isEmpty method is O(1). Any set for which isEmpty() returns true is considered the “empty set” (∅) for purposes of union, intersection, and complement described below. iterator() The iterator method returns an Iterator over the elements in this set. Although the interface specifies that no particular order can be assumed (by a client), the LinkedSet implementation must ensure that the resulting iterator returns the elements in ascending natural order. The associated performance constraints are as follows: iterator(): O(1); hasNext(): O(1); next(): O(1); required space: O(1). Set Operator Methods of the Set Interface These methods correspond to the basic mathematical set operations. Each method takes a parameter of type Set; that is, an object of some class that implements the Set interface. Since the implementing class is unknown, it may or may not be a LinkedSet. Thus, none of these methods can assume that the parameter set maintains its elements in any particular order. equals(Set s) Two sets are equal if and only if they contain exactly the same elements, regardless of order. If A = {1,2,3},B = {3,1,2}, and C = {1,2,3,4}, then A = B and A != C. The equals method returns true if this set is equal to the parameter set, and false otherwise. The time complexity of the equals method must be O(N^2) where N is the size of each set. union(Set s) The union of set A with set B, denoted A ∪ B, is defined as {x | x ∈ A or x ∈ B}. Note that A ∪ B = B ∪ A and A ∪ ∅ = A. The union method returns a set that is the union of this set and the parameter set. The result set must be in ascending natural order. The time complexity of the union method must be O(N^2) where N is the size of the larger of the two sets involved. intersection(Set s) The intersection of set A with set B, denoted A ∩ B, is defined as {x | x ∈ A and x ∈ B}. Note that A ∩ B = B ∩ A and A ∩ ∅ = ∅. The intersection method returns a set that is the intersection of this set and the parameter set. The result set must be in ascending natural order. The time complexity of the intersection method must be O(N^2) where N is the size of the larger of the two sets involved. complement(Set s) The relative complement of set B with respect to set A, denoted A B, is defined as {x | x ∈ A and x ∈/ B}. Note that A B != B A, A ∅ = A, and ∅ A = ∅. The complement method returns a set that is the relative complement of the parameter set with respect to this set. The result set must be in ascending natural order. The time complexity of the complement method must be O(N^2) where N is the size of the larger of the two sets involved. Additional Methods of the LinkedSet Class In addition to the methods from the Set interface, the LinkedSet class also implements its own class-specific methods. Most of these methods are designed to take advantage of the underlying representation, while some of them simply provide added functionality. Constructors The only public constructor that is allowed has been provided for you and you must not change it in any way. You may, however, find it helpful to write your own private constructor; one that offers direct support for building an LinkedSet from an existing doubly-linked list. Such a constructor will be helpful but it is not required and will not be graded. equals(LinkedSet s) The external behavior of this overloaded method is identical to the equals method from the Set interface described above. However, since the parameter is typed as an LinkedSet, this method can directly access the doubly-linked list in this set as well as in the parameter set. Having access to the underlying representation of both sets allows a more efficient algorithm for this method. The time complexity of this equals method must be O(N) where N is the size of this set. union(LinkedSet s) The external behavior of this overloaded method is identical to the union method from the Set interface described above. However, since the parameter is typed as an LinkedSet, this method can directly access the doubly-linked list in this set as well as in the parameter set. Having access to the underlying representation of both sets allows a more efficient algorithm for this method. The time complexity of the union method must be O(N) where N is the size of the larger of the two sets involved. intersection(LinkedSet s) The external behavior of this overloaded method is identical to the intersection method from the Set interface described above. However, since the parameter is typed as an LinkedSet, this method can directly access the doubly-linked list in this set as well as in the parameter set. Having access to the underlying representation of both sets allows a more efficient algorithm for this method. The time complexity of the intersection method must be O(N) where N is the size of the larger of the two sets involved. complement(LinkedSet s) The external behavior of this overloaded method is identical to the complement method from the Set interface described above. However, since the parameter is typed as an LinkedSet, this method can directly access the doubly-linked list in this set as well as in the parameter set. Having access to the underlying representation of both sets allows a more efficient algorithm for this method. The time complexity of the complement method must be O(N) where N is the size of the larger of the two sets involved. descendingIterator() The descendingIterator method returns an Iterator over the elements in this set in descending natural order. The associated performance constraints are as follows: descendingIterator(): O(1); hasNext(): O(1); next(): O(1); required space: O(1). powerSetIterator() The power set of a set S, denoted P(S), is defined as {T | T ⊆ S}; that is, the set of all subsets of S. There are 2^N members of P(S) where N is the number of elements in S. For example, if S = {A,B,C}, then P(S) = {∅, {A}, {B}, {C}, {A,B}, {B,C}, {A,C}, {A,B,C}}. (Note that the empty set ∅ is a member of every set.) The powersetIterator method returns an Iterator over the elements in the power set of this set. The iterator makes no guarantees regarding the order in which the elements of P(S) will be returned. The associated time complexities are as follows: powerSetIterator(): O(N); hasNext(): O(1); next(): O(N); required space: O(N), where N is the size of this set.

$25.00 View

[SOLVED] Comp2210 autocomplete

Autocomplete, or predictive text, is now a common feature in software applications including search engines, messaging apps, source code editors and more. Its more aggressive cousin autocorrect can be extremely frustrating and sometimes funny. But when done well, providing predicted completions to something currently being typed can be helpful and can make the task go faster. We’re probably all familiar with how autocomplete works: As a user types, the software predicts the most likely completions of what the user is typing and offers these as selectable options. This works best when the set of possible completions is constrained and there is a clear basis for making predictions of which are most likely. For example, when a user types myString., a source code editor that offers code completion can confidently offer a set of method signatures as possible completions based on the methods available for the object’s type. Deciding which method is most likely is a different matter, but we could guess at how that might be done. Similarly, when a user types “See you “, a messaging app could offer completion options such as “later” and “soon”, perhaps based on a history of past messages the user has typed. An autocomplete application not only has to provide useful and accurate predictions, but it has to do so quickly. If making predictions is too slow or if its operation in any way slows down the actual task being performed, autocomplete becomes a liability that would quickly be disabled by the user. User experience studies suggest that response and rendering of interactive results must be done within a 50ms to 0.1 second timeframe. For an autocomplete application to scale up while meeting that hard time constraint, the underlying algorithms will have to have low-order time complexity. The importance of both correctness (making useful predictions) and efficiency (making predictions very quickly) is demonstrated at scale in the autocomplete applications used by search engines like Google Search. Google Search must compute and render meaningful predictions with each keystroke for billions of searches each day. Now that’s scalability. So how would an autocomplete application actually work? Well, that’s exactly what this assignment will help us to figure out. Problem Description You must develop the components of an autocomplete application. To keep things simple, we will assume that our autocomplete application will work in the context of something like a search engine. Autocomplete will take in a string (we’ll call it a prefix) and will output a list of likely completions (we’ll call each a query). So, a user could type a portion of a query and autocomplete would offer a list of predictions of the completed query that the user intends to complete. The strings can contain any Unicode character except newline. Our autocomplete application can only work in one context at a time. For example, if we want to let users search for movie titles, we would have to load needed movie title data first. Once loaded, autocomplete can predict possible full movie titles based on a given prefix. Likewise, if we want to provide word completion similar to messaging apps, our autocomplete application would have to load needed word data first. Once loaded, autocomplete can predict possible whole words based on a given prefix. The data that the autocomplete application needs will be a set of (query, weight) pairs that represent all possible completions. Each query will be a complete search query (like a complete movie title) that a user might want to search for. Each weight will be a non-negative integer that is a distinguishing attribute of the query that will be used for the purposes of ranking queries: The larger the weight, the more “likely” the query. For example, in a word-based autocomplete for a messaging app the individual queries would be words, and weights would be the frequency of occurrence; thus making more frequently used words the more likely predictions of autocomplete. Here are the first few lines of a data source of English words. the 23135851162 of 13151942776 and 12997637966 to 12136980858 a 9081174698 in 8469404971 for 5933321709 is 4705743816 on 3750423199 that 3400031103 Each line consists of a word (query) and an integer (weight). The integer records the total number of occurrences of the associated word in some large corpus of English text. Note the data is arranged in descending order of weight. This data shows that “the” is the most frequently occurring English word, appearing over 23 billion times in the corpus from which the data was drawn. So, if “t” is the prefix, the autocomplete should return “the”, “to”, and “that” – in that order – as the first three predicted completions. Solution Approach and Framework We will develop our autocomplete application in terms of three classes: Term, BinarySearch, and Autocomplete. The Term class Term is used to represent a (query, weight) pair. You must write this class so that it is completely consistent with the following API. public class Term implements Comparable { /** * Initialize a term with the given query and weight. * This method throws a NullPointerException if query is null, * and an IllegalArgumentException if weight is negative. */ public Term(String query, long weight) { } /** * Compares the two terms in descending order of weight. */ public static Comparator byDescendingWeightOrder() { } /** * Compares the two terms in ascending lexicographic order of query, * but using only the first length characters of query. This method * throws an IllegalArgumentException if length is less than or equal * to zero. */ public static Comparator byPrefixOrder(int length) { } /** * Compares this term with the other term in ascending lexicographic order * of query. */ @Override public int compareTo(Term other) { } /** * Returns a string representation of this term in the following format: * query followed by a tab followed by weight */ @Override public String toString(){ } } Note that Term supports comparison by three different orders: (1) lexicographic order (the natural order), descending order of weight (one alternate ordering), and lexicographic order using only the first length characters of the query string (a family of alternate orderings). By providing three different comparison methods, we are able to sort terms in three different orders. All three orders will be important in delivering the autocomplete functionality. The BinarySearch class BinarySearch provides two search methods, both of which are variants of the classic binary search presented in lecture. When binary searching a sorted array that contains more than one key equal to the search key, the client may want to know the index of either the first or last matching key. public class BinarySearch { /** * Returns the index of the first key in a[] that equals the search key, * or -1 if no such key exists. This method throws a NullPointerException * if any parameter is null. */ public static int firstIndexOf(Key[] a, Key key, Comparator comparator) { } /** * Returns the index of the last key in a[] that equals the search key, * or -1 if no such key exists. This method throws a NullPointerException * if any parameter is null. */ public static int lastIndexOf(Key[] a, Key key, Comparator comparator) { } } Both methods must use the binary search algorithm and make on the order of log N comparisons to a[middle] where N is the number of elements in a[]. The Autocomplete class Autocomplete uses the Term and BinarySearch class to provide complete autocomplete functionality for a given set of strings and weights. public class Autocomplete { /** * Initializes a data structure from the given array of terms. * This method throws a NullPointerException if terms is null. */ public Autocomplete(Term[] terms) { } /** * Returns all terms that start with the given prefix, in descending order of weight. * This method throws a NullPointerException if prefix is null. */ public Term[] allMatches(String prefix) { } } The constructor must store the contents of terms in its own internal array and then sort this array in natural order (lexicographic order of query). The allMatches method must use the binary search methods to identify the range of methods that begin with the given prefix and return these elements in an array sorted in descending order of weight. This returned array represents the predicted completions for the given prefix.

$25.00 View

[SOLVED] Comp2210 collection selector

This assignment focuses on implementing the methods of a class much like java.util.Collections. The Selector.java file defines a class with static methods that implement polymorphic algorithms that operate on and/or return Collections. Each method of Selector is very clearly specified, is independent of the other methods in the class, and is designed to provide relatively simple functionality. So, this is a great context for practicing what we’ve been discussing in lecture – generalized programming and test-based verification. The Selector class You must correctly implement all the method bodies of the provided Selector class. Your implementation must adhere exactly to the API of the Selector class, as described in the provided source code comments and as described below. public class Selector { public static T min(Collection c, Comparator comp) public static T max(Collection c, Comparator comp) public static T kmin(Collection c, int k, Comparator comp) public static T kmax(Collection c, int k, Comparator comp) public static Collection range(Collection c, T low, T high, Comparator comp) public static T ceiling(Collection c, T key, Comparator comp) public static T floor(Collection c, T key, Comparator comp) } The sections that follow provide details of each method’s behavior as well as specific examples. The min method. This method selects the minimum value from a given collection, as defined by a given comparator. If either the collection or comparator is null, this method throws an IllegalArgumentException. If the collection is empty, the method throws a NoSuchElementException. The collection must not be changed by this method. Examples: T c comp min(c, comp) Integer [2, 8, 7, 3, 4] ascending order 2 Integer [5, 9, 1, 7, 3] descending order 9 Integer [8, 7, 6, 5, 4] ascending order 4 (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] ascending by String field (A,5) (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] ascending by Integer field (E,1) 1 The max method. This method selects the maximum value from a given collection, as defined by a given comparator. If either the collection or comparator is null, this method throws an IllegalArgumentException. If the collection is empty, the method throws a NoSuchElementException. The collection must not be changed by this method. Examples: T c comp max(c, comp) Integer [2, 8, 7, 3, 4] ascending order 8 Integer [5, 9, 1, 7, 3] descending order 1 Integer [8, 7, 6, 5, 4] ascending order 8 (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] ascending by String field (E,1) (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] ascending by Integer field (A,5) The kmin method. This method selects the k th minimum value from a given collection, as defined by a given comparator. A value is the k th minimum if there are exactly k−1 values less than it in the collection. If either the collection or comparator is null, this method throws an IllegalArgumentException. If the collection is empty or if there is no k th minimum value, this method throws a NoSuchElementException. Note that there is no k th minimum value if k is less than 1, k is greater than the number of elements in the collection, or if k is greater than the number of distinct values in the collection. The collection must not be changed by this method. Examples: T c k comp kmin(c, k, comp) Integer [2, 8, 7, 3, 4] 1 ascending order 2 Integer [5, 9, 1, 7, 3] 2 descending order 7 Integer [8, 7, 6, 5, 4] 3 ascending order 6 (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] 4 ascending by String field (D,2) (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] 2 ascending by Integer field (D,2) The kmax method. This method selects the k th maximum value from a given collection, as defined by a given comparator. A value is the k th maximum if there are exactly k − 1 values greater than it in the collection. If either the collection or comparator is null, this method throws an IllegalArgumentException. If the collection is empty or if there is no k th minimum value, this method throws a NoSuchElementException. Note that there is no k th minimum value if k is less than 1, k is greater than the number of elements in the collection, or if k is greater than the number of distinct values in the collection. The collection must not be changed by this method. Examples: T c k comp kmax(c, k, comp) Integer [2, 8, 7, 3, 4] 1 ascending order 8 Integer [5, 9, 1, 7, 3] 2 descending order 3 Integer [8, 7, 6, 5, 4] 3 ascending order 6 (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] 4 ascending by String field (B,4) (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] 2 ascending by Integer field (B,4) Page 2 of 4 The range method. This method returns a collection of all values i from a given collection such that low ≤ i ≤ high, as defined by the given comparator, including duplicate values. (Note that low and high do not have to be actual values in the given collection.) The returned collection contains only values in the range [low..high], and no others. If there are no qualifying values, including the case where c is empty, this method throws a NoSuchElementException. This method throws an IllegalArgumentException if either the collection or comparator is null. The collection is not changed by this method. Examples: T c low high comp range(c, low, high, comp) Integer [2, 8, 7, 3, 4] 1 5 ascending order [2,3,4] Integer [5, 9, 1, 7, 3] 3 5 ascending order [5,3] Integer [5, 9, 1, 7, 3] 5 3 descending order [5,3] Integer [8, 7, 6, 5, 4] 4 8 ascending order [8, 7, 6, 5, 4] (String, Integer) [(A,5), (B,4), (C,3)] (B,3) (C,5) asc. by String field [(B,4),(C,3)] (String, Integer) [(A,5), (B,4), (C,3)] (F,4) (G,7) asc. by Integer field [(A,5),(B,4)] The ceiling method. This method returns the smallest value i in a given collection such that i ≥ key, as defined by the given comparator. (Note that key does not have to be an actual value in the given collection.) If the given collection or comparator is null, this method throws an IllegalArgumentException. If the collection is empty or if there is no qualifying value i, this method throws a NoSuchElementException. Examples: T c key comp ceiling(c, key, comp) Integer [2, 8, 7, 3, 4] 1 ascending order 2 Integer [5, 9, 1, 7, 3] 7 descending order 7 Integer [8, 7, 6, 5, 4] 0 ascending order 4 (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] (B,9) ascending by String field (B,4) (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] (F,0) ascending by Integer field (E,1) The floor method. This method returns the largest value i in a given collection such that i ≤ key, as defined by the given comparator. (Note that key does not have to be an actual value in the given collection.) If the given collection or comparator is null, this method throws an IllegalArgumentException. If the collection is empty or if there is no qualifying value i, this method throws a NoSuchElementException. Examples: T c key comp floor(c, key, comp) Integer [2, 8, 7, 3, 4] 6 ascending order 4 Integer [5, 9, 1, 7, 3] 1 descending order 1 Integer [8, 7, 6, 5, 4] 9 ascending order 8 (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] (F,0) ascending by String field (E,1) (String, Integer) [(A,5), (B,4), (C,3), (D,2), (E, 1)] (B,9) ascending by Integer field (A,5) Page 3 of 4 Notes and other requirements Here are other specific requirements, notes, and suggestions. • Read this handout carefully. Read the provided source code carefully. Ask questions on Piazza. Start early and be proactive. • The constructor has been completed for you and must not be changed in any way. • You may add any number of private methods that you like, but you may not add any public method or constructor, nor may you change the signature of any public method or constructor. • You must not add any fields, either public or private, to the Selector class. • You must not add any import statements to those already in the Selector class. • You may not change or delete any import statement in the Selector class. • You may not use fully-qualified names to circumvent the restrictions on imports above, except in the one instance noted below. • None of the methods in the Selector class can modify the Collection parameter in any way. More generally, the methods in the Selector class should have no side-effects. • You are only allowed to use sorting as part of your solution to kmin and kmax. You are not required to use sorting, but you are allowed to do so for these two methods only. If you use sorting, you must do so by calling the java.util.Collections.sort(List, Comparator) method. You must use the fully-qualified name (no importing Collections) and you are allowed at most two calls to this method – at most one in kmin and at most one in kmax. • The use of the ArrayList class is allowed only in kmin, kmax, and range. No other method is allowed to use any implementing class of Collection. • The declaration or use of an array in any method is strictly prohibited. • Your code must be type safe; that is, your code must compile cleanly with no compiler warnings.

$25.00 View

[SOLVED] Comp2210 array selector

This assignment focuses on implementing the methods of a class much like java.util.Arrays. The Selector.java file defines a class with static methods designed to provide useful functionality on arrays, with the common theme of selecting values in an array with particular properties. Each method of Selector is clearly specified, is independent of the other methods in the class, and is designed to provide relatively simple functionality. So, this is a great context in which to practice systematic, disciplined development and test-based verification. The Selector class You must correctly implement all the method bodies of the provided Selector class. Your implementation must adhere exactly to the API of the Selector class, as described in the provided source code comments and as described below. A brief description of each method is provided below, along with examples of its use. Refer to the Selector.java source code file for the complete specification of each method’s required behavior. The min method This method selects the minimum value from a given array. Examples: The max method This method selects the maximum value from a given array. Examples: The kmin method This method selects the k-th minimum (smallest) value from a given array. A value is the k-th minimum if and only if there are exactly k – 1 distinct values strictly less than it in the array. Note that kmin(a, 1) == min(a) and kmin(a, a.length()) == max(a). Examples: The kmax method This method selects the k-th maximum (largest) value from a given array. A value is the k-th maximum if and only if there are exactly k – 1 distinct values strictly greater than it in the array. Note that kmax(a, 1) == max(a) and kmax(a, a.length()) == min(a). Examples: The range method This method selects all values from a given array that are greater than or equal to low and less than or equal to high. The floor method This method selects from a given array the largest value that is less than or equal to key. Examples: The ceiling method This method selects from a given array the smallest value that is greater than or equal to key. Examples: Notes and Other Requirements ● The Selector.java source code file is provided in the startercode folder in Vocareum. You can download Selector.java from Vocareum and work on your local machine. ● The comments provided in Selector.java describe the required behavior of each method. ● The constructor of the Selector class has been written for you and it must not be changed in any way. ● You may add any number of private methods that you like, but you may not add any public method or constructor, nor may you change the signature of any public method or constructor. ● You must not add any fields, either public or private, to the Selector class. ● The java.util.Arrays class has been imported for you. You are free to delete this import statement if you do not use any methods from the Arrays class in your solutions. ● You may not add any other import statement, and you may not use another resource from the java.util package. The penalty for violating this constraint will be a deduction of points up to 50% of the total points available on the assignment. ● You may not use sorting in any method, except for kmin and kmax. The penalty for violating this constraint will be a deduction of points up to 50% of the total points available on the assignment. ● You do not have to use sorting in kmin and kmax, but doing so makes the solution more straightforward. If you choose to use sorting in these two methods, I suggest that you use the sort(int[]) method from the java.util.Arrays class.

$25.00 View

[SOLVED] Comp1210 project: bakery – part 3

Overview: This project is Part 3 of three that involves a bakery and reporting for baked items. In Part 1, you developed Java classes that represent categories of baked items including cookies, pies, cakes, and wedding cakes. In Part 2, you implemented additional classes: (1) PriceComparator, which implements the Comparator interface to compare baked items by price; (2) FlavorComparator, which implements the Comparator interface to compare baked items by flavor; (3) BakeryItemList, Project: Bakery – Part 3 Page 2 of 7 Page 2 of 7 which represents a list of baked items and includes several specialized methods. In Part 3, you are to add exception handling. You will need to do the following: (1) create a new class named InvalidCategoryException which extends the Exception class, (2) add try-catch statements to catch a FileNotFoundException in the main method of the BakeryPart3 class, and (3) modify the readItemFile method in the BakedItemList class to catch/handle the InvalidCategoryException, NumberFormatException, and NoSuchElementException in the event that one or more of these exceptions are thrown while reading the input file. Note that the main method in BakeryPart3 should create a BakedItemList object and then invoke the readItemFile method on that BakedItemList object to read data from a file and add baked items to the list. You can use BakeryPart3 in conjunction with interactions by running the program in the canvas (or debugger with a breakpoint) and single stepping until the variables of interest are created. You can then enter interactions in the usual way. In addition to the source files, you will create a JUnit test file for the indicated source files and write one or more test methods to ensure the classes and methods meet the specifications. You should create a jGRASP project upfront and then add the source files as they are created. All of your files should be in a single folder. • Cookie, Pie, Cake, and WeddingCake Requirements and Design: No changes from the specifications in Bakery – Part 1. • PriceComparator and FlavorComparator Requirements and Design: No changes from the specifications in Bakery – Part 2. • InvalidCategoryException.java Requirements and Design: InvalidCategoryException is a user defined exception created by extending the Exception class. This exception is to be thrown and caught in the readItemFile method in the BakedItemList class when a line of input data contains an invalid baked item category. The constructor for InvalidCategoryException takes a single String parameter representing category and invokes the super constructor with the following String: “For category: ” + “”” + category + “”” This string will be the toString() value of an InvalidCategoryException when it occurs. For a similar constructor, see InvalidLengthException.java in ExamplesPolygons from the class notes on Exceptions. • BakedItemList.java Requirements and Design: The BakedItemList class provides methods for reading in the data file and generating reports. Design: In addition to the specifications in Bakery – Part 2, the existing readItemFile method must be modified to catch the following: InvalidCategoryException, NumberFormatException, and NoSuchElementException. Project: Bakery – Part 3 Page 3 of 7 Page 3 of 7 o readItemFile has no return value and accepts the data file name as a String. Remember to include the throws FileNotFoundException clause in the method declaration. This method creates a Scanner object to read in the file, and then reads the file line by line. The first line contains the BakedItemList name and each of the remaining lines contains the data for a baked item. After reading in the list name, the “baked item” lines should be processed as follows. A baked item line is read in, a second scanner is created on the line, and the individual values for the baked item are read in. After the values on the line have been read in, an “appropriate” BakedItem object is created. The data file is a “comma separated values” file; i.e., if a line contains multiple values, the values are delimited by commas. So when you set up the scanner for the baked item lines, you need to set the delimiter to use a “,” by calling the useDelimiter(“,”) method on the Scanner object. Each baked item line in the file begins with a category for the baked item (C, P, K, and W are valid categories for baked items indicating Cookie, Pie, K for Cake, and WeddingCake respectively). The second field in the record is the name, followed by flavor, and quantity. The next field(s) may correspond, as appropriate, to the data needed for the particular category (or subclass) of BakedItem (e.g., a Pie has a crustCost and a Cake has layers). The last fields are the ingredients, which should be stored in an array (new String[50]) as they are read in. After all ingredients have been read in, use the java.util.Arrays copyOf method make a new ingredients array with length equal to the number of ingredients. If the line/record has a valid category and it has been successfully read in, the appropriate BakedItem object should be created and added to itemList. For each incorrect line scanned (i.e., a line of data contains an invalid category, invalid numeric data, or missing data), your method will need to handle the invalid items properly. o If the line of data begins with an invalid category, your program should throw an InvalidCategoryException (see description above). The code that adds a record with an invalid baked item category to the excluded records array should be placed in the catch block for InvalidCategoryException. o If a line of data has a valid category, but includes invalid numeric data (e.g., the value for quantity contains an alphabetic character), a NumberFormatException (see notes on last page) will be thrown automatically by the Java Runtime Environment (JRE). o If a line of data has a valid category but has missing data, a java.util.NoSuchElementException will be thrown automatically by the JRE. The code in the while loop that reads in the baked item records and checks for baked item category should be in a try statement followed by three catch blocks: one for each of InvalidCategoryException, NumberFormatException, and NoSuchElementException (fully qualify as java.util.NoSuchElementException or include import statement). In each catch block, a String object should be created consisting of “*** ” + e + ” in: ” + line where e is the exception and line is the record with the invalid data. The String object should be added to the excludedRecords array. The file baked_item_data2.csv is available for download from the course web site. Below are example data records (the first line/record containing the baked item list name is Project: Bakery – Part 3 Page 4 of 7 Page 4 of 7 followed by baked item lines/records). Note that five of these baked item records will cause an exception to be thrown. These are listed in the “Excluded Records Report” on page 6. Auburn’s Best Bakery C,Chips Delight,Chocolate Chip,12,flour,sugar,dark chocolate chips,butter,baking soda,salt D,Chips Delight,Chocolate Chip,12,flour,sugar,dark chocolate chips,butter,baking soda,salt P,Weekly Special,Apple,1,0,flour,sugar,apple,cinnamon,butter,baking soda,salt P,Daily Special,Pecan,1.0,0,flour,sugar,pecans,dark corn syrup,butter,baking soda,salt R,Weekly Special,Apple,1,0,flour,sugar,apple,cinnamon,butter,baking soda,salt P,Summer Special,Key Lime,1,2.0,flour,sugar,lime juice,lemon juice,graham crackers,butter,baking soda,salt K,Birthday,Chocolate,1,1,flour,sugar,cocoa powder,vanilla,eggs,butter,baking soda,baking powder,salt K,2-Layer,Red Velvet,1,2,flour,sugar,cocoa powder,food coloring,eggs,butter,baking soda,baking powder,salt K,2-Layer,Chocolate,1,two,flour,sugar,cocoa powder,eggs,butter,baking soda,baking powder,salt W,3-Layer/3-Tier,Buttermilk,1,3 W,3-Layer/3-Tier,Vanilla,1,3,3,flour,sugar,buttermilk,coffee,eggs,butter,baking soda,baking powder,salt BakeryPart3.java Requirements and Design: The BakeryPart3 class has only a main method as described below. In addition to the specifications in Bakery – Part 2, the main method should be modified to catch and handle an FileNotFoundException if one is thrown in the readItemFile method. o As before, the main method reads in the file name as the first argument, args[0], of the command line arguments, creates an instance of BakedItemList, and then calls the readItemFile method in the BakedItemList class to read in the data file and generate the five reports as shown in the output examples beginning on the next page. The main method should not include the throws FileNotFoundException in the declaration. Instead, the main method should include a try-catch statement to catch FileNotFoundException when/if it is thrown in the readItemFile method in the BakedItemList class. This exception is most likely to occur when an incorrect file name is passed to the readItemFile method. After this exception is caught and the appropriate message is printed in the main method, your program should end. See the second example output below. Example data files can be downloaded from the Lab web page, and the program output for baked_item_data2.csv begins on the next page. Example Output when file name is missing as command line argument —-jGRASP exec: java BakeryPart3 File name expected as command line argument. Program ending. —-jGRASP: operation complete. Example Output when attempting to read a file that is not found (fake_data.csv) —-jGRASP exec: java BakeryPart3 fake_data.csv Attempted to read file: fake_data.csv (No such file or directory) Program ending. —-jGRASP: operation complete. Project: Bakery – Part 3 Page 5 of 7 Page 5 of 7 Example Output for baked_item _data2.csv —-jGRASP exec: java BakeryPart3 baked_item_data2.csv ————————————— Report for Auburn’s Best Bakery ————————————— Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apple, cinnamon, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) ————————————— Report for Auburn’s Best Bakery (by Class) ————————————— Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apple, cinnamon, butter, baking soda, salt) WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) ————————————— Report for Auburn’s Best Bakery (by Price) ————————————— Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Project: Bakery – Part 3 Page 6 of 7 Page 6 of 7 Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apple, cinnamon, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) ————————————— Report for Auburn’s Best Bakery (by Flavor) ————————————— Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apple, cinnamon, butter, baking soda, salt) Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) ————————————— Excluded Records Report ————————————— *** InvalidCategoryException: For category: “D” in: D,Chips Delight,Chocolate Chip,12,flour,sugar,dark chocolate chips,butter,baking soda,salt *** java.lang.NumberFormatException: For input string: “1.0” in: P,Daily Special,Pecan,1.0,0,flour,sugar,pecans,dark corn syrup,butter,baking soda,salt *** InvalidCategoryException: For category: “R” in: R,Weekly Special,Apple,1,0,flour,sugar,apple,cinnamon,butter,baking soda,salt *** java.lang.NumberFormatException: For input string: “two” in: K,2-Layer,Chocolate,1,two,flour,sugar,cocoa powder,eggs,butter,baking soda,baking powder,salt *** java.util.NoSuchElementException in: W,3-Layer/3-Tier,Buttermilk,1,3 —-jGRASP: operation complete. Project: Bakery – Part 3 Page 7 of 7 Page 7 of 7 Notes: 1. This project assumes that you are reading each double or int value as String using next() and then parsing it into a double with Double.parseDouble(…) or into an int with Integer.parseInt(…) as shown in the following examples. . . . Double.parseDouble(myInput.next()); . . . Integer.parseInt(myInput.next()); This form of input will throw a java.lang.NumberFormatException if the value is not a double. If you are reading in each double value as a double using nextDouble(), for example . . . myInput.nextDouble(); then a java.util.InputMismatchException will be thrown if the value read is not a double. For this project, you must use Double.parseDouble(…) or Integer.parseInt(…) to input a double or int value respectively since Web-CAT is expecting NumberFormatException when an input String cannot be converted to double or int value. 2. In the readItemFile method, for the default case (or else), which detects an invalid category, the only statement should be: throw new InvalidCategoryException(category); The code that was in this block in Part 2 should be moved to the catch block for InvalidCategoryException with any changes specified for Part 3.

$25.00 View

[SOLVED] Comp1210 project: bakery – part 2

Overview: This project is Part 2 of three that involves a bakery and reporting for baked items. In Part 1, you developed Java classes that represent categories of baked items including cookies, pies, cakes, and wedding cakes. In Part 2, you will implement four additional classes: (1) PriceComparator, which implements the Comparator interface to compare baked items by price; (2) FlavorComparator, which implements the Comparator interface to compare baked items by flavor; (3) Project: Bakery – Part 2 Page 2 of 9 Page 2 of 9 BakeryItemList, which represents a list of baked items and includes several specialized methods; and (4) BakeryPart2, which contains the main method for the program. Note that the main method in BakeryPart2 should declare a BakeryItemList object and then call the readItemFile method which will add baked items to the BakeryItemList as the data is read in from a file. You can use BakeryPart2 in conjunction with interactions by running the program in the canvas (or debugger with a breakpoint) and single stepping until the variables of interest are created. You can then enter interactions in the usual way. In addition to the source files, you will create a JUnit test file for each class and write one or more test methods to ensure the classes and methods meet the specifications. You should create a jGRASP project upfront and then add the source and test files as they are created. All of your files should be in a single folder. • Cookie, Pie, Cake, and WeddingCake Requirements and Design: No changes from the specifications in Part 1. • BakedItem.java Requirements and Design: In addition to the specifications in Part 1, the BakedItem class should implement the Comparable interface for BakedItem, which means the following method must be implemented in BakedItem. o compareTo: Takes a BakedItem as a parameter and returns an int indicating the ordering from lowest to highest based on the class name followed name, and flavor. Since this is essentially the same as the toString value, you could do the compareTo based on toString value. Otherwise, to do this, you will need to extract the class name, name, and flavor from the BakedItem and do the compareTo based these. Regardless of the method you use, to avoid uppercase and lowercase issues you should make the String values either all uppercase or all lowercase prior to comparing them. • BakedItemList.java Requirements: The BakedItemList class provides methods for reading in the data file and generating reports. Design: The BakedItemList class has fields, a constructor, and methods as outlined below. (1) Fields: All fields below should be private. (a) listName is a String that represents the name of the BakedItemList. (b) itemList is an array that can hold up to 100 BakedItem objects. (c) itemCount is an int that tracks the number of BakedItem objects in the itemList array. (d) excludedRecords is an array that can hold up to 30 String elements representing records that are read from the data file but not processed. (e) excludedCount is an int that tracks the number of records that have been added to the excludedRecords array. (f) listCount is a static field of type int initialized to zero, which tracks the number of BakedItemList objects created. Project: Bakery – Part 2 Page 3 of 9 Page 3 of 9 (2) Constructor: The constructor has no parameters, initializes the instance fields in BakedItemList as follows: listName = “”; itemList = new BakedItem[100]; itemCount = 0; excludedRecords = new String[30]; excludedCount = 0; The constructor should also increment the static field listCount. The readItemFile method defined below will populate the BakedItemList object. (3) Methods: Usually a class provides methods to access and modify each of its instance variables (i.e., getters and setters) along with any other required methods. The methods for BakedItemList are described below. o getListName returns the String representing the listName. o setListName has no return value, accepts a String, and then assigns it to listName. o getItemList returns the BakedItem array representing the itemList. o setItemList has no return value, accepts a BakedItem array, and then assigns it to itemList (used in conjunction with setItemCount to provide a new BakedItem array and itemCount). o getItemCount returns the current value of itemCount. o setItemCount has no return value, accepts an int, and assigns it to itemCount. o getExcludedRecords returns the String array representing the excludedRecords. o setExcludedRecords has no return value, accepts a String array, and then assigns it to excludedRecords (used in conjunction with setExcludedCount to provide a new excluded records array and new excluded records count). o getExcludedCount returns the current value of excludedCount. o setExcludedCount has no return value, accepts an int, and sets excludedCount to it. o getListCount is a static method that returns the current value of listCount. o resetListCount is a static method that has no return value and sets listCount to 0. o readItemFile has no return value and accepts the data file name as a String. Remember to include the throws FileNotFoundException clause in the method declaration. This method creates a Scanner object to read in the file, and then reads the file line by line. The first line contains the BakedItemList name and each of the remaining lines contains the data for a baked item. After reading in the list name, the “baked item” lines should be processed as follows. A baked item line is read in, a second scanner is created on the line, and the individual values for the baked item are read in. After the values on the line have been read in, an “appropriate” BakedItem object is created. The data file is a “comma separated values” file; i.e., if a line contains multiple values, the values are delimited by commas. So when you set up the scanner for the baked item lines, you need to set the delimiter to use a “,” by calling the useDelimiter(“,”) method on the Scanner object. Each baked item line in the file begins with a category for the baked item (C, P, K, and W are valid categories for baked items indicating Cookie, Pie, K for Cake, and WeddingCake respectively). The second field in the record is the name, followed by flavor, and quantity. The next field(s) may correspond, as appropriate, to the data needed for the particular category (or subclass) of BakedItem (e.g., a Pie has a crustCost and a Cake has layers). The last fields are the ingredients, which should be stored in an array (new String[50]) as they are read in. After all ingredients have been read in, use the java.util.Arrays copyOf method make a new Project: Bakery – Part 2 Page 4 of 9 Page 4 of 9 ingredients array with length equal to the number of ingredients. If the line/record has a valid category and it has been successfully read in, the appropriate BakedItem object should be created and added to itemList. If an item line has an invalid category, no BakedItem is created and the line should be added to the excluded records array with the String “*** invalid category *** for line: ” appended to the front of it, and the excluded count should be incremented. The file baked_item_data.csv is available for download from the course web site. Below are example data records (the first line/record containing the BakedItemList name is followed by baked item lines/records): Auburn’s Best Bakery C,Chips Delight,Chocolate Chip,12,flour,sugar,dark chocolate chips,butter,baking soda,salt D,Chips Delight,Chocolate Chip,12,flour,sugar,dark chocolate chips,butter,baking soda,salt P,Weekly Special,Apple,1,0,flour,sugar,apple,cinnamon,butter,baking soda,salt R,Weekly Special,Apple,1,0,flour,sugar,apple,cinnamon,butter,baking soda,salt P,Summer Special,Key Lime,1,2.0,flour,sugar,lime juice,lemon juice,graham crackers,butter,baking soda,salt K,Birthday,Chocolate,1,1,flour,sugar,cocoa powder,vanilla,eggs,butter,baking soda,baking powder,salt K,2-Layer,Red Velvet,1,2,flour,sugar,cocoa powder,food coloring,eggs,butter,baking soda,baking powder,salt W,3-Layer/3-Tier,Vanilla,1,3,3,flour,sugar,buttermilk,coffee,eggs,butter,baking soda,baking powder,salt o generateReport processes the item list array using the original order from the file to produce the bakery Report which is returned as a String. See the example output on pages 7 – 8. o generateReportByClass makes a copy of the item list array and sorts the copy using the natural ordering, then processes the sorted array to produce the bakery Report (by Class) which is returned as a String. See the example output on pages 7 – 9. o generateReportByPrice makes a copy of the item list array and sorts the copy by item price, then processes the sorted array to produce the bakery Report (by Price) which is returned as a String. See the example output on pages 7 – 8. o generateReportByFlavor makes a copy of the item list array and sorts the copy by flavor, then processes the sorted array to produce the bakery Report (by Flavor) which is returned as a String. See the example output on pages 7 – 8. o generateExcludedRecordsReport processes the excludedRecords array to produce the Excluded Records Report which is returned as a String. See the example output on pages 7 – 8. Code and Test: See examples of file reading and sorting (using Arrays.sort) in the class notes. The natural sorting order for BakedItem objects is determined by the compareTo method from the Comparable interface. If itemList is the variable for the array of BakedItem objects, it can be sorted with the following statement. BakedItem[] bList = Arrays.copyOf(itemList, itemCount); Arrays.sort(bList); The sorting order based on item price is determined by the PriceComparator class which implements the Comparator interface (described below). It can be sorted with the following statement. BakedItem[] bList = Arrays.copyOf(itemList, itemCount); Arrays.sort(bList, new PriceComparator()); Project: Bakery – Part 2 Page 5 of 9 Page 5 of 9 The sorting order based on boarding cost is determined by the FlavorComparator class which implements the Comparator interface (described below). It can be sorted with statements similar to those above, except that a new FlavorComparator is passed to the Arrays.sort method.• PriceComparator.java Requirements and Design: The PriceComparator class implements the Comparator interface for BakedItem objects. Hence, it implements the following method. o compare(BakedItem b1, BakedItem b2)that defines the ordering from lowest to highest based on the price of the baked item. Note that the compare method is the only method in the PriceComparator class. An instance of this class will be used as one of the parameters when the Arrays.sort method is used to sort by “price”. For an example of a class implementing Comparator, see class notes on Comparing Objects. • FlavorComparator.java Requirements and Design: The FlavorComparator class implements the Comparator interface for BakedItem objects. Hence, it implements the following method. o compare(BakedItem b1, BakedItem b2)that defines the ordering from lowest to highest (i.e., alphabetical order, ignoring case) based on the flavor of each baked item. Note that the compare method is the only method in the FlavorComparator class. An instance of this class will be used as one of the parameters when the Arrays.sort method is used to sort by “flavor”. For an example of a class implementing Comparator, see class notes on Comparing Objects. • BakeryPart2.java Requirements and Design: The BakeryPart2 class has only a main method as described below. o main reads in the file name as the first argument, args[0], of the command line arguments, creates an instance of BakedItemList, and then calls the readItemFile method in the BakedItemList class to read in the data file and generate the five reports as shown in the output examples beginning on page 7. Since main invokes the readItemFile method, which throws the FileNotFoundException, main should also throw FileNotFoundException. If no command line argument is provided (i.e., args.length == 0), the program should indicate this and end as shown in the first example output on page 7. An example data file, baked_item_data.csv can be downloaded from the Lab assignment web page, and this file will be available in Web-CAT for use with your test files. Any .csv data files that you create for your test methods will need to be uploaded to Web-CAT along with your source and test files. Project: Bakery – Part 2 Page 6 of 9 Page 6 of 9 Code and Test: In your JUnit test file for the BakeryPart2 class, you should have at least two test methods for the main method. One test method should invoke BakeryPart2.main(args) where args is an empty String array, and the other test method should invoke BakeryPart2.main(args) where args[0] is the String representing the data file name. Depending on how you implemented the main method, these two test methods should cover the code in main. In the first test method, you should reset listCount, call your main method, then assert that getListCount()is zero for the test with no file name. In the second test method, you should reset listCount, call your main method assert that getListCount()is one with baked_item_data.csv as the file name passed in as args[0]. In the first test method, you can invoke main with no command line argument as follows: // You should be checking for args.length == 0 // in BakeryPart2, and the following should exercise // the code for true. BakedItemList.resetListCount(); String[] args1 = {}; // an empty String[] BakeryPart2.main(args1); Assert.assertEquals(“Baked Item List count should be 0. “, 0, BakedItemList.getListCount()); In the second test method, you can invoke main as follows with the file name as the first (and only) command line argument: BakedItemList.resetListCount(); String[] args2 = {“baked_item_data.csv”}; // element args2[0] is the file name BakeryPart2.main(args2); Assert.assertEquals(“Baked Item List count should be 1. “, 1, BakedItemList.getListCount()); If Web-CAT complains that the default constructor for BakeryPart2 has not been covered, you should include the following line of code in one of your test methods. // to exercise the default constructor BakeryPart2 app = new BakeryPart2(); Project: Bakery – Part 2 Page 7 of 9 Page 7 of 9 Example Output when no file name is provided as a command line argument —-jGRASP exec: java BakeryPart2 File name expected as command line argument. Program ending. —-jGRASP: operation complete. Example Output when baked_item_data.csv is the command line argument —-jGRASP exec: java BakeryPart2 baked_item_data.csv ————————————— Report for Auburn’s Best Bakery ————————————— Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apple, cinnamon, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) ————————————— Report for Auburn’s Best Bakery (by Class) ————————————— Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apple, cinnamon, butter, baking soda, salt) WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) Project: Bakery – Part 2 Page 8 of 9 Page 8 of 9 ————————————— Report for Auburn’s Best Bakery (by Price) ————————————— Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apple, cinnamon, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) ————————————— Report for Auburn’s Best Bakery (by Flavor) ————————————— Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apple, cinnamon, butter, baking soda, salt) Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) ————————————— Excluded Records Report ————————————— *** invalid category *** for line: D,Chips Delight,Chocolate Chip,12,flour,sugar,dark chocolate chips,butter,baking soda,salt *** invalid category *** for line: R,Weekly Special,Apple,1,0,flour,sugar,apple,cinnamon,butter,baking soda,salt —-jGRASP: operation complete. Project: Bakery – Part 2 Page 9 of 9 Page 9 of 9 Hints 1. In the methods that generate the reports, return value should begin with a and end with . The beginning is part of the heading, and the ending is part of the line for last BakedItem appended to the return value in the list. Note that you need to use a loop to go through the array of BakedItem objects to add each to the report. Each BakedItem added to the report should begin with and end with . 2. In the main method, use println, rather than print, to print each report. You should not need to add any characters before or after the report method is invoked within the println statement. For example, the following statement could be used to generate the first report where bList is a BakedList object: System.out.println(bList.generateReport()); 3. If a baked item line has an invalid category, add “*** invalid category *** ” plus the entire line read in from the file to the excluded record array. For example, the following record has an invalid category (D). D,Chips Delight,Chocolate Chip,12,flour,sugar,dark chocolate chips,butter,baking soda,salt This would result in the following two lines when the excluded record is eventually printed as part of the report. *** invalid category *** for line: D,Chips Delight,Chocolate Chip,12,flour,sugar,dark chocolate chips,butter,baking soda,salt

$25.00 View

[SOLVED] Comp1210 project: bakery – part 1

Overview: This project is the first of three that will involve a bakery and reporting for baked items. You will develop Java classes that represent categories of baked item including cookie, pie, cake, and wedding cake. Note that there is no requirement for a class with a main method in this project. You will need to create a JUnit test file for the indicated classes and write one or more test methods to ensure the classes and methods meet the specifications. You should create a jGRASP project and add the source and test files as they are created. All your files should be in a single folder. The UML class diagram at right provides a visual overview of how the classes in the project relate to one another. As you add your classes to the jGRASP project, you should generate the UML class diagram by double-clicking for the project in the Open Projects window. Once generated, you can use the mouse to select/drag a class to arrange the diagram similar to the one shown. Alternatively, select BakedItem, right-click on it and select Layout > Tree Down, then select Dependents of Selected. Project: Bakery – Part 1 Page 2 of 7 Page 2 of 7 You should read through the remainder of this assignment before you start coding. • BakedItem.java Requirements: Create an abstract BakedItem class that stores BakedItem data and provides methods to access the data. Design: The BakedItem class has fields, a constructor, and methods as outlined below. (1) Fields: instance variables for the BakedItem’s name of type String, the flavor type String, the quantity of type int, and ingredients of type String[]; static (or class) variable of type int for the count of BakedItem objects that have been created (set to zero when declared and incremented in the constructor). These variables should be declared with the protected access modifier so that they are accessible in the subclasses of BakedItem. These are the only fields that this class should have. (2) Constructor: The BakedItem class must contain a constructor that accepts four parameters representing the values to be assigned to the instance fields: name, flavor, quantity, and ingredients. The last parameter (e.g., ingredientIn) should be a variable length parameter (i.e., String…ingredientsIn), which will be type String[] in the constructor body. Since this class is abstract, the constructor will be called from the subclasses of BakedItem using super and the parameter list. The count field should be incremented in this constructor. (3) Methods: Usually a class provides methods to access (or read) and modify each of its instance variables (known as get and set methods) along with any other required methods. At minimum you will need the following methods. o getName: Accepts no parameters and returns a String representing the name. o setName: Accepts a String representing the name, sets the field, and returns nothing. o getFlavor: Accepts no parameters and returns a String representing the flavor. o setFlavor: Accepts a String representing the flavor, sets the field, and returns nothing. o getQuantity: Accepts no parameters and returns a int representing quantity. o setQuantity: Accepts an int representing the quantity, sets the field, and returns nothing. o getIngredients: Accepts no parameters and returns a String[] representing ingredients. o setIngredients: Accepts a variable length parameter (i.e., String…ingredientsIn) representing the ingredients, which will be type String[] in the method body, sets the field, and returns nothing. o getCount: Accepts no parameters and returns an int representing the count. Since count is static, this method should be static as well. Project: Bakery – Part 1 Page 3 of 7 Page 3 of 7 o resetCount: Accepts no parameters, resets count to zero, and returns nothing. Since count is static, this method should be static as well. o toString: Returns a String describing the BakedItem object. This method will be inherited by the subclasses and should be declared public final so that it cannot be overriden. The double value for the price() should be formatted (“$#,##0.00”), but the numeric value for quantity does not require formatting. Below is an example of the toString result when called on a Cookie object of the Cookie class described below. Note that “Cookie” is the class name which is followed by name and flavor separated by a dash. Quantity and Price are preceded by three spaces. The ingredients, which are enclosed in parentheses, begin on a new line and are separated by commas. Also, there should be at most five ingredients on a line. For example, “salt” is the sixth ingredient so it was printed on the next line. Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Note that you can get the class name for the instance by calling this.getClass().toString().substring(6). For the example Cookie c, this.getClass().toString() returns “class Cookie” and substring(6) extracts the class name “Cookie” which begins at character 6. This approach allows the toString method in BakedItem to work for all subclasses that inherit the toString method. o price: An abstract method that accepts no parameters and returns a double representing the price for a BakedItem. Since this is an abstract method, it has no body in BakedItem; however, each non-abstract subclass of BakedItem must implement this method. Code and Test: Since BakedItem is abstract, you cannot create instances to test. You will need to use instances of a subclass, e.g., Cookie, which specified below. Thus, it is common to test the methods in an abstract class in the test file for the first non-abstract subclass (i.e., Cookie). • Cookie.java Requirements: Derive the class Cookie from BakedItem. Design: The Cookie class has fields, a constructor, and methods as outlined below. (1) Fields: a class variable (a constant) BASE_RATE of type double, which is declared with the public, static, and final modifiers and initialized to 0.35. This is the only field that should be declared in this class. (2) Constructor: The Cookie class must contain a constructor that accepts four parameters representing the four instance fields in the BakedItem class (name, flavor, quantity, and ingredients). Since this class is a subclass of BakedItem, the super constructor should be called with field values for BakedItem. Below is an example of how the constructor could be used to create a Cookie object: Cookie c = new Cookie(“Chips Delight”, “Chocolate Chip”, 12, “flour”, “sugar”, “dark chocolate chips”, “butter”, “baking soda”, “salt”); Project: Bakery – Part 1 Page 4 of 7 Page 4 of 7 (3) Methods: Usually a class provides methods to access (or read) and modify each of its instance variables (known as get and set methods) along with any other required methods. You will need to implement the following price method but not the toString method. o price: Accepts no parameters and returns a double representing the price for the Cookie calculated as follows: BASE_RATE * quantity. o toString: None – this method is inherited from BakedItem. An example of the return value is shown below for Cookie c created above. Note that Quantity and Price are preceded by three spaces. Cookie: Chips Delight – Chocolate Chip Quantity: 12 Price: $4.20 (Ingredients: flour, sugar, dark chocolate chips, butter, baking soda, salt) Code and Test: As you implement the Cookie class, you should compile and test it as methods are created. Although you could use interactions, it should be more efficient to test by creating appropriate JUnit test methods. You can now continue developing the methods in BakedItem (parent class of Cookie). The test methods in CookieTest should be used to test the methods in both BakedItem and Cookie. Remember, Cookie is-a BakedItem which means Cookie inherited the instance methods defined in BakedItem. Therefore, you can create instances of Cookie to test methods of the BakedItem class.• Pie.java Requirements: Derive the class Pie from BakedItem. Design: The Pie class has a field, a constructor, and methods as outlined below. (1) Field: an instance variable for crust cost of type double, which is declared with the private access modifier; a class variable (a constant) BASE_RATE of type double, which is declared with the public, static, and final modifiers and initialized to 12.0. These are the only fields that should be declared in this class. (2) Constructor: The Pie class must contain a constructor that accepts five parameters representing the four instance fields in the BakedItem class and the one instance field crust cost declared in Pie (name, flavor, quantity, crust cost, and ingredients). Since this class is a subclass of BakedItem, the super constructor should be called with field values for BakedItem. Below are examples of how the constructor could be used to create a Pie p1 (without a crust cost) and Pie p2 (with a crust cost of $2). Pie p1 = new Pie(“Weekly Special”, “Apple”, 1, 0, “flour”, “sugar”, “apples”, “cinnamon”, “butter”, “baking soda”, “salt”); Pie p2 = new Pie(“Summer Special”, “Key Lime”, 1, 2.0, “flour”, “sugar”, “lime juice”, “lemon juice”, “graham crackers”, “butter”, “baking soda”, “salt”); Project: Bakery – Part 1 Page 5 of 7 Page 5 of 7 (3) Methods: Usually a class provides methods to access (or read) and modify each of its instance variables (known as get and set methods) along with any other required methods. You will need to implement the following getCrustCost, setCrustcost, and price methods but not the toString method. o getCrustCost: Accepts no parameters and returns a double representing crust cost. o setCrustCost: Accepts double for crust cost, sets the field, and returns nothing. o price: Accepts no parameters and returns a double representing the price for a Pie calculated as follows: (BASE_RATE + crustCost) * quantity. o toString: NONE. When toString is invoked on an instance of Pie, the toString method inherited from BakedItem is called. Below is an example of the toString result for Pie p1 as it is declared above. Pie: Weekly Special – Apple Quantity: 1 Price: $12.00 (Ingredients: flour, sugar, apples, cinnamon, butter, baking soda, salt) Pie: Summer Special – Key Lime Quantity: 1 Price: $14.00 (Ingredients: flour, sugar, lime juice, lemon juice, graham crackers, butter, baking soda, salt) Code and Test: As you implement the Pie class, you should compile and test it as methods are created by using a combination of interactions and JUnit test methods. For example, as soon you have implemented and successfully compiled the constructor, you should create an instance of Pie in interactions. Remember that when you have an instance on the workbench, you can unfold it to see its values. After you have implemented and compiled one or more of the methods, you should begin creating test methods in the corresponding PieTest.java file.• Cake.java Requirements: Derive the class Cake from class BakedItem. Design: The Cake class has a field, a constructor, and methods as outlined below. (1) Field: instance variable for layers of type int, which should be declared with the protected access modifier; a class variable (a constant) BASE_RATE of type double, which is declared with the public, static, and final modifiers and initialized to 8. These are the only fields that should be declared in this class. (2) Constructor: The Cake class must contain a constructor that accepts five parameters representing the four instance fields in the BakedItem class and the one instance field layers declared in Cake (name, flavor, quantity, layers, and ingredients). Since this class is a subclass of BakedItem, the super constructor should be called with field values for BakedItem. Below is an example of how the constructor could be used to create a Cake c1 with one layer and Cake c2 with two layers. Project: Bakery – Part 1 Page 6 of 7 Page 6 of 7 Cake c1 = new Cake(“Birthday”, “Chocolate”, 1, 1, “flour”, “sugar”, “cocoa powder”, “vanilla”, “eggs”, “butter”, “baking soda”, “baking powder”, “salt”); Cake c2 = new Cake(“2-Layer”, “Red Velvet”, 1, 2, “flour”, “sugar”, “cocoa powder”, “food coloring”, “eggs”, “butter”, “baking soda”, “baking powder”, “salt”);(3) Methods: Usually a class provides methods to access (or read) and modify each of its instance variables (known as get and set methods) along with any other required methods. You will need to implement the following getLayers, setLayers, and price methods but not the toString method. o getLayers: Accepts no parameters and returns an int representing layers. o setLayers: Accepts an int representing layers, sets the field, and returns nothing. o price: Accepts no parameters and returns a double representing the price for the Cake calculated as follows: (BASE_RATE * layers) * quantity. o toString: None – this class uses the toString method inherited from BakedItem. An example of the return value is shown below for Cake c1 and Cake c2 created above. Note that Quantity and Price are preceded by three spaces. Cake: Birthday – Chocolate Quantity: 1 Price: $8.00 (Ingredients: flour, sugar, cocoa powder, vanilla, eggs, butter, baking soda, baking powder, salt) Cake: 2-Layer – Red Velvet Quantity: 1 Price: $16.00 (Ingredients: flour, sugar, cocoa powder, food coloring, eggs, butter, baking soda, baking powder, salt) Code and Test: As you implement the Cake class, you should compile and test it as methods are created by using a combination of interactions and JUnit test methods. For example, as soon you have implemented and successfully compiled the constructor, you should create an instance of Cake in interactions. Remember that when you have an instance on the workbench, you can unfold it to see its values. After you have implemented and compiled one or more of the methods, you should begin creating test methods in the corresponding CakeTest.java file.• WeddingCake.java Requirements: Derive the class WeddingCake from Cake. Design: The WeddingCake class has a fields, a constructor, and methods as outlined below. (1) Fields: instance variables for tiers of type int which should be declared with the private access modifier; a class variable (a constant) BASE_RATE of type double, which is declared with the public, static, and final modifiers and initialized to 15.0. These are the only fields that should be declared in this class. Project: Bakery – Part 1 Page 7 of 7 Page 7 of 7 (2) Constructor: The WeddingCake class must contain a constructor that accepts six parameters representing the four values for the instance fields in the BakedItem and two for the instance fields declared in Cake and WeddingCake respectively (name, flavor, quantity, layers, tiers, and ingredients). Since this class is a subclass of Cake, the super constructor should be called with five values for Cake. Below is an example of how the constructor could be used to create a WeddingCake object. WeddingCake c3 = new WeddingCake(“3-Layer/3-Tier”, “Vanilla”, 1, 3, 3, “flour”, “sugar”, “buttermilk”, “coffee”, “eggs”, “butter”, “baking soda”, “baking powder”, “salt”); (3) Methods: Usually a class provides methods to access (or read) and modify each of its instance variables (known as get and set methods) along with any other required methods. You will need to implement the following getTiers, setTiers, and price methods but not the toString method. o getTiers: Accepts no parameters and returns an int representing tiers. o setTiers: Accepts an int representing tiers, sets the field, and returns nothing. o price: Accepts no parameters and returns a double representing the price for a WeddingCake calculated as follows: (BASE_RATE * layers * tiers) * quantity. o toString: None – this class uses the toString method inherited from BakedItem. An example of the return value is shown below for WeddingCake c3 created above. Note that Quantity and Price are preceded by three spaces. WeddingCake: 3-Layer/3-Tier – Vanilla Quantity: 1 Price: $135.00 (Ingredients: flour, sugar, buttermilk, coffee, eggs, butter, baking soda, baking powder, salt) Code and Test: As you implement the WeddingCake class, you should compile and test it as methods are created by using a combination of interactions and JUnit test methods. For example, as soon you have implemented and successfully compiled the constructor, you should create an instance of WeddingCake in interactions. Remember that when you have an instance on the workbench, you can unfold it to see its values. After you have implemented and compiled one or more of the methods, you should begin creating test methods in the corresponding WeddingCakeTest.java file.UML Class Diagram: If you have not already done so, add your classes to the jGRASP project, then generate the UML class diagram by double-clicking for the project in the Open Projects window. Once generated, you can use the mouse to select/drag a class to arrange the diagram like the one on page 1. Alternatively, select BakedItem, right-click on it and select Layout > Tree Down, then select Dependents of Selected.

$25.00 View

[SOLVED] Comp1210 project: ringtorus with junit tests – part 3

Overview: This project consists of four classes: (1) RingTorus is a class representing a RingTorus object; (2) RingTorusTest class is a JUnit test class which contains one or more test methods for each method in the RingTorus class; (3) RingTorusList is a class representing a RingTorus list object; and (4) RingTorusListTest class is a JUnit test class which contains one or more test methods for each method in the RingTorusList class. Note that there is no requirement for a class with a main method in this project. You should create a new folder to hold the files for this project and add your files from Part 2 (RingTorus.java file and RingTorusTest.java). You should create a new jGRASP project for Part 3 and add RingTorus.java file and RingTorusTest.java to the project; you should see the two files in their respective categories – Source Files and Test Files. If RingTorusTest.java appears in source File category, you should right-click on the file and select “Mark As Test” from the right-click menu. Project: RingTorus with JUnit Tests – Part 3 Page 2 of 9 Page 2 of 9 You will then be able to run the test file by clicking the JUnit run button on the Open Projects toolbar. After RingTorusList.java and RingTorusListTest.java are created as specified below, these should be added to your jGRASP project for Part 3 as well. If you have successfully completed RingTorus.java and RingTorusTest.java in Part 2, you should go directly to RingTorusList.java on page 6. • RingTorus.java (new items for this class in Part 2 are underlined) Requirements: Create a RingTorus class that stores the label, small radius, and large radius where the small radius is less than the large radius and both are positive. The RingTorus class also includes methods to set and get each of these fields, as well as methods to calculate the outside diameter, surface area, and volume of a RingTorus object, and a method to provide a String value that describes a RingTorus object. The RingTorus class includes a one static field (or class variable) to track the number of RingTorus objects that have been created, as well appropriate static methods to access and reset this field. And finally, this class provides a method that JUnit will use to test RingTorus objects for equality as well as a method required by Checkstyle. In addition, RingTorus must implement the Comparable interface for objects of type RingTorus. Design: The RingTorus class implements the Comparable interface for objects of type RingTorus and has fields, a constructor, and methods as outlined below (last method is new). (1) Fields: Instance Variables – label of type String, large radius of type double, and small radius of type double. Initialize the String to “” and the double variables to 0 in their respective declarations. These instance variables should be private so that they are not directly accessible from outside of the RingTorus class, and these should be the only instance variables (fields) in the class. Class Variable – count of type int should be private and static, and it should be initialized to zero in the declaration. (2) Constructor: Your RingTorus class must contain a public constructor that accepts three parameters (see types of above) representing the label, large radius, and small radius. Instead of assigning the parameters directly to the fields, the respective set method for each field (described below) should be called since they are checking the validity of the parameter. For example, instead of using the statement label = labelIn; use the statement setLabel(labelIn); After setLabel is called be sure to call setLargeRadius before calling setSmallRadius. The constructor should increment the class variable count each time a RingTorus is constructed. Below are examples of how the constructor could be used to create RingTorus objects. Note that although String and numeric literals are used for the actual parameters (or arguments) in these examples, variables of the required type could have been used instead of the literals. Project: RingTorus with JUnit Tests – Part 3 Page 3 of 9 Page 3 of 9 RingTorus ex1 = new RingTorus (“Small Example”, 9.5, 1.25); RingTorus ex2 = new RingTorus (” Medium Example “, 35.1, 10.4); RingTorus ex3 = new RingTorus (“Large Example”, 134.28, 32.46); (3) Methods: Usually a class provides methods to access and modify each of its instance variables (known as get and set methods) along with any other required methods. The methods for RingTorus, which should each be public, are described below. See the formulas in the figure above and the Code and Test section below for information on constructing these methods. o getLabel: Accepts no parameters and returns a String representing the label field. o setLabel: Takes a String parameter and returns a boolean. If the String parameter is not null, then the “trimmed” String is set to the label field and the method returns true. Otherwise, the method returns false and the label is not set. o getLargeRadius: Accepts no parameters and returns a double representing the large radius field. o setLargeRadius: Takes a double parameter and returns a boolean. If the double parameter is positive and is greater than the current small radius, then the parameter is assigned to the large radius field and the method returns true. Otherwise, the method returns false and the large radius field is not set. o getSmallRadius: Accepts no parameters and returns a double representing the small radius field. o setSmallRadius: Takes a double parameter and returns a boolean. If the double parameter is positive and is less than the current large radius, then the parameter is assigned to the small radius field and the method returns true. Otherwise, the method returns false and the small radius field is not set. o diameter: Accepts no parameters and returns a double representing the diameter of the RingTorus. See formula in figure on page 1. o surfaceArea: Accepts no parameters and returns the double value for the surface area of the RingTorus. See formula in figure on page 1. o volume: Accepts no parameters and returns the double value for the volume of the RingTorus. See formula in figure on page 1. o toString: Returns a String containing the information about the RingTorus object formatted as shown below, including decimal formatting (“#,##0.0##”) for the double values. Newline and tab escape sequences should be used to achieve the proper layout within the String but it should not begin or end with a newline. In addition to the field values (or corresponding “get” methods), the following methods should be used to compute appropriate values in the toString method: diameter(), surfaceArea(), and volume(). Each line should have no trailing spaces (e.g., there should be no spaces before a newline ( ) character). The toString value for ex1, ex2, and ex3 respectively are shown below (the blank lines are not part of the toString values). Project: RingTorus with JUnit Tests – Part 3 Page 4 of 9 Page 4 of 9 RingTorus “Small Example” large radius = 9.5 units small radius = 1.25 units diameter = 21.5 units surface area = 468.806 square units volume = 293.004 cubic units RingTorus “Medium Example” large radius = 35.1 units small radius = 10.4 units diameter = 91.0 units surface area = 14,411.202 square units volume = 74,938.248 cubic units RingTorus “Large Example” large radius = 134.28 units small radius = 32.46 units diameter = 333.48 units surface area = 172,075.716 square units volume = 2,792,788.867 cubic units o getCount: A static method that accepts no parameters and returns an int representing the static count field. o resetCount: A static method that returns nothing, accepts no parameters, and sets the static count field to zero. o equals: An instance method that accepts a parameter of type Object and returns false if the Object is a not a RingTorus; otherwise, when cast to a RingTorus, if it has the same field values (ignoring case in the label field) as the RingTorus upon which the method was called, it returns true. Otherwise, it returns false. Note that this equals method with parameter type Object will be called by the JUnit Assert.assertEquals method when two RingTorus objects are checked for equality. Below is a version you are free to use. public boolean equals(Object obj) {if (!(obj instanceof RingTorus )) { return false; } else { RingTorus rt = (RingTorus ) obj; return (label.equalsIgnoreCase(rt.getLabel()) && (Math.abs(largeRadius – rt.getLargeRadius()) < .000001) && (Math.abs(smallRadius – rt.getSmallRadius()) < .000001)); } } o hashCode(): Accepts no parameters and returns zero of type int. This method is required by Checkstyle if the equals method above is implemented. o compareTo: Accepts a parameter of type RingTorus and returns an int as follows: a negative value if this.volume() is less than the parameter’s volume; a positive value Project: RingTorus with JUnit Tests – Part 3 Page 5 of 9 Page 5 of 9 if this.volume() is greater than the parameter’s volume; zero if the two volumes are essentially equal. For a hint, see the activity for this module. Code and Test: As you implement the methods in your RingTorus class, you should compile it and then create test methods as described below for the RingTorusTest class. When using the setSmallRadius and setLargeRadius, the values of the current smallRadius and largeRadius must be considered to decide the order in which you invoke the associated set methods. For setSmallRadius, the “new” small radius must be positive and smaller the current large radius, and for setLargeRadius, the “new” large radius must be positive and larger the current small radius. For example, a new RingTorus object has its smallRadius and largeRadius fields initialized to zero in the field declaration, which is default initial value for doubles. However, this means in the constructor, you must invoke the setLargeRadius before the setSmallRadius. If you wanted a small radius of 2.5 and attempt to set it first, it would not be set since it will not be less than largeRadius, which is initially zero. Thus, you invoke setLargeRadius first since any positive value will be greater than the smallRadius which is initially zero. Therefore, in general you need to consider the current value the smallRadius and largeRadius to decide the order you invoke the associated set methods. • RingTorusTest.java Requirements: Create a RingTorusTest class that contains a set of test methods to test each of the methods in RingTorus. The goal for Part 2 is method, statement, and condition coverage. Design: Typically, in each test method, you will need to create an instance of RingTorus, call the method you are testing, and then make an assertion about the expected result and the actual result (note that the actual result is commonly the result of invoking the method unless it has a void return type). You can think of a test method as simply formalizing or codifying what you could be doing in jGRASP interactions to make sure a method is working correctly. That is, the sequence of statements that you would enter in interactions to test a method should be entered into a single test method. You should have sufficient test methods so that each method, statement, and condition in RingTorus are covered. Collectively, these test methods are a set of test cases that can be invoked with a single click to test all the methods in your RingTorus class. Code and Test: A good strategy would be to begin by writing test methods for those methods in RingTorus that you “know” are correct. By doing this, you will be able to concentrate on the getting the test methods correct. That is, if the test method fails, it is most likely due to a defect in the test method itself rather the RingTorus method being testing. As you become more familiar with the process of writing test methods, you will be better prepared to write the test methods as new methods are developed. Be sure to call the RingTorus toString method in one of your test methods and assert something about the return value. If you do not want to use assertEquals, which would require the return value match the expected value exactly, you could use assertTrue and check that the return value contains the expected value. For example, for RingTorus example3: Assert.assertTrue(example3.toString().contains(“”Large Example””)); Project: RingTorus with JUnit Tests – Part 3 Page 6 of 9 Page 6 of 9 Also, remember that you can set a breakpoint in a JUnit test method and run the test file in Debug mode. Then, when you have an instance in the Debug tab, you can unfold it to see its values or you can open a canvas window and drag items from the Debug tab onto the canvas. You can also step-in to the method being called by the test method and then single-step through it, looking for the error. • RingTorusList.java (new for Part 3) – Consider implementing this file in parallel with its test file, RingTorusListTest.java, which is described after this class. Requirements: Create a RingTorusList class that stores the name of the list and an array of RingTorus objects. It also includes methods that return the name of the list, number of RingTorus objects in the RingTorusList, total surface area, total volume, average surface area, and average volume for all RingTorus objects in the RingTorusList. The toString method returns summary information about the list (see below). Design: The RingTorusList class has three fields, a constructor, and methods as outlined below. (1) Fields (or instance variables): (1) a String representing the name of the list, (2) an array of RingTorus objects, and (3) an int representing the number of RingTorus objects in the array, which may be less than the length of the array of RingTorus objects. These instance variables should be private so that they are not directly accessible from outside of the RingTorusList class. These should be the only fields (or instance variables) in this class, and they should be initialized in the constructor described below. (2) Constructor: Your RingTorusList class must contain a constructor that accepts three parameters: (1) a parameter of type String representing the name of the list, (2) a parameter of type RingTorus[], representing the list of RingTorus objects, and (3) a parameter of type int representing the number of RingTorus objects in the array. These parameters should be used to assign the fields described above (i.e., the instance variables). (3) Methods: The methods for RingTorusList are described below. o getName: Returns a String representing the name of the list. o numberOfRingToruses: Returns an int (the value of the third field in the RingTorusList object) representing the number of RingTorus objects in the RingTorusList. o totalDiameter: Returns a double representing the total diameters for all RingTorus objects in the list. If there are zero RingTorus objects in the list, zero should be returned. o totalSurfaceArea: Returns a double representing the total surface areas for all RingTorus objects in the list. If there are zero RingTorus objects in the list, zero should be returned. o totalVolume: Returns a double representing the total volumes for all RingTorus objects in the list. If there are zero RingTorus objects in the list, zero should be returned. Project: RingTorus with JUnit Tests – Part 3 Page 7 of 9 Page 7 of 9 o averageDiameter: Returns a double representing the average diameter for all RingTorus objects in the list. If there are zero RingTorus objects in the list, zero should be returned. o averageSurfaceArea: Returns a double representing the average surface area for all RingTorus objects in the list. If there are zero RingTorus objects in the list, zero should be returned. o averageVolume: Returns a double representing the average volume for all RingTorus objects in the list. If there are zero RingTorus objects in the list, zero should be returned. o toString: Returns a String (does not begin with ) containing the name of the list (which can change depending on the name of the list passed as a parameter to the constructor) followed by various summary items: number of RingToruses, total surface area, total volume, average surface area, and average volume. Use “#,##0.0##” as the pattern to format the double values. Below is an example of the formatted String returned by the toString method, where the name of the list (name field) is RingTorus Test List and the array of RingTorus objects contains the three examples described above (top of page 3). —– Summary for RingTorus Test List —– Number of RingToruses: 3 Total Diameter: 445.98 units Total Surface Area: 186,955.724 square units Total Volume: 2,868,020.119 cubic units Average Diameter: 148.66 units Average Surface Area: 62,318.575 square units Average Volume: 956,006.706 cubic units o getList: Returns the array of RingTorus objects (the second field above). o addRingTorus: Returns nothing but takes three parameters (label, large radius, and small radius), creates a new RingTorus object, and adds it to the RingTorusList object in the next available location in the RingTorus array. Be sure to increment the int field containing the number of RingTorus objects in the RingTorusList object. o findRingTorus: Takes a label of a RingTorus as the String parameter and returns the corresponding RingTorus object if found in the RingTorusList object; otherwise returns null. Case should be ignored when attempting to match the label. o deleteRingTorus: Takes a String as a parameter that represents the label of the RingTorus and returns the RingTorus if it is found in the RingTorusList object and deleted; otherwise returns null. Case should be ignored when attempting to match the label. When an element is deleted from an array, elements to the right of the deleted element must be shifted to the left. After shifting the items to the left, the last RingTorus element in the array should be set to null. Finally, the number of elements field must be decremented. o editRingTorus: Takes three parameters (label, large radius, and small radius), uses the label to find the corresponding the RingTorus object in the list. If found, sets the large radius and small radius fields to the values passed in as parameters, and returns true. If not found, returns false. (Note that the label should not be changed by this method.) o findRingTorusWithLargestVolume: Returns the RingTorus with the largest volume; if the list contains no RingTorus objects, returns null. Project: RingTorus with JUnit Tests – Part 3 Page 8 of 9 Page 8 of 9 Code and Test: Some of the methods above require that you use a loop to go through the objects in the array. You should implement the class below in parallel with this one to facilitate testing. That is, after implementing one to the methods above, you can implement the corresponding test method in the test file described below. • RingTorusListTest.java (new for Part 3) – Consider implementing this file in parallel with its source file, RingTorusList.java, which is described above this class. Requirements: Create a RingTorusListTest class that contains a set of test methods to test each of the methods in RingTorusList. Design: Typically, in each test method, you will need to create an instance of RingTorusList, call the method you are testing, and then make an assertion about the expected result and the actual result (note that the actual result is usually the result of invoking the method unless it has a void return type). You can think of a test method as simply formalizing or codifying what you have been doing in interactions to make sure a method is working correctly. That is, the sequence of statements that you would enter in interactions to test a method should be entered into a single test method. You should have at least one test method for each method in RingTorusList. However, if a method contains conditional statements (e.g., an if statement) that results in more than one distinct outcome, you need a test method for each outcome. For example, if the method returns boolean, you should have one test method where the expected return value is false and another test method that expects the return value to be true. Also, each condition in boolean expression must be exercised true and false. Collectively, these test methods are a set of test cases that can be invoked with a single click to test all the methods in your RingTorusList class. Code and Test: A good strategy would be to begin by writing test methods for those methods in RingTorusList that you “know” are correct. By doing this, you will be able to concentrate on the getting the test methods correct. That is, if the test method fails, it is most likely due to a defect in the test method itself rather the RingTorusList method being testing. As you become more familiar with the process of writing test methods, you will be better prepared to write the test methods for the new methods in RingTorusList. Be sure to call the RingTorusList toString method in one of your test cases so that the grading system will consider the toString method to be “covered” in its coverage analysis. Remember that when a test method fails, you can set a breakpoint in a JUnit test method and run the test file in Debug mode. Then, when you have an instance in the Debug tab, you can unfold it to see its values or you can open a canvas window and drag items from the Debug tab onto the canvas. You can also step-in to the method being called by the test method and then single-step through it, looking for the error. Finally, when comparing two arrays for equality in JUnit, be sure to use Assert.assertArrayEquals rather than Assert.assertEquals. Assert.assertArrayEquals will return true only if the two arrays are the same length and the elements are equal based on an element-by-element comparison using the equals method. Project: RingTorus with JUnit Tests – Part 3 Page 9 of 9 Page 9 of 9 The Grading System When you submit your files (RingTorus.java, RingTorusTest.java, RingTorusList.java, and RingTorusListTest.java), the grading system will use the results of your test methods and their level of coverage of your source files as well as the results of our reference correctness tests to determine your grade. In this project, your test files should provide method, statement, and condition coverage. Each condition in your source file must be exercised both true and false. See below for a description of how to test a boolean expression with multiple conditions. To see your code coverage in Web-CAT, on “Your Assignment Submission Results” page, in “File Details”, click on your source file and look for any highlighted lines of code. Hover your mouse on the highlighted source code, to see the hint about what was not covered. Example of hints you might see include: (1) This line was never executed by your tests. (2) Not all possibilities of this decision were tested. Remember that when you have N simple conditions combined, you must test all N+1 possibilities. Note For Testing the equals Method Perhaps the most complicated method to test is the equals method in RingTorus. This method has three conditions in the boolean expression that are &&’d. Since Java (and most other languages) uses short-cut logic, if the first condition in an && is false, the &&’d expression is false. This means that to test the second condition, the first conditions must be true. Furthermore, to test the third conditions both the first and second conditions must be true. To have condition coverage for the equals method, you need the four test cases where the three conditions evaluate to the following, where T is true, F is false, and X is don’t care (could be true or false): FXX – returns false TFX – returns false TTF – returns false TTT – returns true Note For Testing the Methods with Two &&’d Conditions Your setSmallRadius and setLargeRadius methods likely each have two conditions in the boolean expression that are &&’d. Since Java (and most other languages) uses short-cut logic, if the first condition in an && is false, the &&’d expression itself is false (without considering the second condition). This means that to test the second condition, the first condition must be true. To have condition coverage for the equals method, you need the three test cases where the two conditions evaluate to the following, where T is true, F is false, and X is don’t care (could be true or false): FX – returns false TF – returns false TT – returns false

$25.00 View

[SOLVED] Comp1210 project: ringtorus with junit tests – part 2

Overview: In this project, the two files developed in Part 1 are to be extended as follows: (1) RingTorus, which is a class representing a RingTorus object, will implement the Comparable interface and (2) RingTorusTest class, which is a JUnit test class, will be expanded from method coverage to condition coverage for RingTorus. The new items for Part 2 are underlined below for your convenience. Note that there is no requirement for a class with a main method in this project. You should create a new folder to hold the files for this project and add your files from Part 1 (RingTorus.java file and RingTorusTest.java). You should create a new jGRASP project for Part 2 and add RingTorus.java file and RingTorusTest.java to the project; you should see the two files in their respective categories – Source Files and Test Files. If RingTorusTest.java appears in source File category, you should right-click on the file and select “Mark As Test” from the right-click menu. Project: RingTorus with JUnit Tests – Part 2 Page 2 of 6 Page 2 of 6 You will then be able to run the test file by clicking the JUnit run button on the Open Projects toolbar. • RingTorus.java (new items for this class in Part 2 are underlined) Requirements: Create a RingTorus class that stores the label, small radius, and large radius where the small radius is less than the large radius and both are positive. The RingTorus class also includes methods to set and get each of these fields, as well as methods to calculate the outside diameter, surface area, and volume of a RingTorus object, and a method to provide a String value that describes a RingTorus object. The RingTorus class includes a one static field (or class variable) to track the number of RingTorus objects that have been created, as well appropriate static methods to access and reset this field. And finally, this class provides a method that JUnit will use to test RingTorus objects for equality as well as a method required by Checkstyle. In addition, RingTorus must implement the Comparable interface for objects of type RingTorus. Design: The RingTorus class implements the Comparable interface for objects of type RingTorus and has fields, a constructor, and methods as outlined below (last method is new). (1) Fields: Instance Variables – label of type String, large radius of type double, and small radius of type double. Initialize the String to “” and the double variables to 0 in their respective declarations. These instance variables should be private so that they are not directly accessible from outside of the RingTorus class, and these should be the only instance variables (fields) in the class. Class Variable – count of type int should be private and static, and it should be initialized to zero in the declaration. (2) Constructor: Your RingTorus class must contain a public constructor that accepts three parameters (see types of above) representing the label, large radius, and small radius. Instead of assigning the parameters directly to the fields, the respective set method for each field (described below) should be called since they are checking the validity of the parameter. For example, instead of using the statement label = labelIn; use the statement setLabel(labelIn); After setLabel is called be sure to call setLargeRadius before calling setSmallRadius. The constructor should increment the class variable count each time a RingTorus is constructed. Below are examples of how the constructor could be used to create RingTorus objects. Note that although String and numeric literals are used for the actual parameters (or arguments) in these examples, variables of the required type could have been used instead of the literals. RingTorus ex1 = new RingTorus (“Small Example”, 9.5, 1.25); RingTorus ex2 = new RingTorus (” Medium Example “, 35.1, 10.4); RingTorus ex3 = new RingTorus (“Large Example”, 134.28, 32.46); Project: RingTorus with JUnit Tests – Part 2 Page 3 of 6 Page 3 of 6 (3) Methods: Usually a class provides methods to access and modify each of its instance variables (known as get and set methods) along with any other required methods. The methods for RingTorus, which should each be public, are described below. See the formulas in the figure above and the Code and Test section below for information on constructing these methods. o getLabel: Accepts no parameters and returns a String representing the label field. o setLabel: Takes a String parameter and returns a boolean. If the String parameter is not null, then the “trimmed” String is set to the label field and the method returns true. Otherwise, the method returns false and the label is not set. o getLargeRadius: Accepts no parameters and returns a double representing the large radius field. o setLargeRadius: Takes a double parameter and returns a boolean. If the double parameter is positive and is greater than the current small radius, then the parameter is assigned to the large radius field and the method returns true. Otherwise, the method returns false and the large radius field is not set. o getSmallRadius: Accepts no parameters and returns a double representing the small radius field. o setSmallRadius: Takes a double parameter and returns a boolean. If the double parameter is positive and is less than the current large radius, then the parameter is assigned to the small radius field and the method returns true. Otherwise, the method returns false and the small radius field is not set. o diameter: Accepts no parameters and returns a double representing the diameter of the RingTorus. See formula in figure on page 1. o surfaceArea: Accepts no parameters and returns the double value for the surface area of the RingTorus. See formula in figure on page 1. o volume: Accepts no parameters and returns the double value for the volume of the RingTorus. See formula in figure on page 1. o toString: Returns a String containing the information about the RingTorus object formatted as shown below, including decimal formatting (“#,##0.0##”) for the double values. Newline and tab escape sequences should be used to achieve the proper layout within the String but it should not begin or end with a newline. In addition to the field values (or corresponding “get” methods), the following methods should be used to compute appropriate values in the toString method: diameter(), surfaceArea(), and volume(). Each line should have no trailing spaces (e.g., there should be no spaces before a newline ( ) character). The toString value for ex1, ex2, and ex3 respectively are shown below (the blank lines are not part of the toString values). RingTorus “Small Example” large radius = 9.5 units small radius = 1.25 units diameter = 21.5 units surface area = 468.806 square units volume = 293.004 cubic units Project: RingTorus with JUnit Tests – Part 2 Page 4 of 6 Page 4 of 6 RingTorus “Medium Example” large radius = 35.1 units small radius = 10.4 units diameter = 91.0 units surface area = 14,411.202 square units volume = 74,938.248 cubic units RingTorus “Large Example” large radius = 134.28 units small radius = 32.46 units diameter = 333.48 units surface area = 172,075.716 square units volume = 2,792,788.867 cubic units o getCount: A static method that accepts no parameters and returns an int representing the static count field. o resetCount: A static method that returns nothing, accepts no parameters, and sets the static count field to zero. o equals: An instance method that accepts a parameter of type Object and returns false if the Object is a not a RingTorus; otherwise, when cast to a RingTorus, if it has the same field values (ignoring case in the label field) as the RingTorus upon which the method was called, it returns true. Otherwise, it returns false. Note that this equals method with parameter type Object will be called by the JUnit Assert.assertEquals method when two RingTorus objects are checked for equality. Below is a version you are free to use. public boolean equals(Object obj) {if (!(obj instanceof RingTorus )) { return false; } else { RingTorus rt = (RingTorus ) obj; return (label.equalsIgnoreCase(rt.getLabel()) && (Math.abs(largeRadius – rt.getLargeRadius()) < .000001) && (Math.abs(smallRadius – rt.getSmallRadius()) < .000001)); } } o hashCode(): Accepts no parameters and returns zero of type int. This method is required by Checkstyle if the equals method above is implemented. o compareTo: Accepts a parameter of type RingTorus and returns an int as follows: a negative value if this.volume() is less than the parameter’s volume; a positive value if this.volume() is greater than the parameter’s volume; zero if the two volumes are essentially equal. For a hint, see the activity for this module. Code and Test: As you implement the methods in your RingTorus class, you should compile it and then create test methods as described below for the RingTorusTest class. Project: RingTorus with JUnit Tests – Part 2 Page 5 of 6 Page 5 of 6 When using the setSmallRadius and setLargeRadius, the values of the current smallRadius and largeRadius must be considered to decide the order in which you invoke the associated set methods. For setSmallRadius, the “new” small radius must be positive and smaller the current large radius, and for setLargeRadius, the “new” large radius must be positive and larger the current small radius. For example, a new RingTorus object has its smallRadius and largeRadius fields initialized to zero in the field declaration, which is default initial value for doubles. However, this means in the constructor, you must invoke the setLargeRadius before the setSmallRadius. If you wanted a small radius of 2.5 and attempt to set it first, it would not be set since it will not be less than largeRadius, which is initially zero. Thus, you invoke setLargeRadius first since any positive value will be greater than the smallRadius which is initially zero. Therefore, in general you need to consider the current value the smallRadius and largeRadius to decide the order you invoke the associated set methods. • RingTorusTest.java Requirements: Create a RingTorusTest class that contains a set of test methods to test each of the methods in RingTorus. The goal for Part 2 is method, statement, and condition coverage. Design: Typically, in each test method, you will need to create an instance of RingTorus, call the method you are testing, and then make an assertion about the expected result and the actual result (note that the actual result is commonly the result of invoking the method unless it has a void return type). You can think of a test method as simply formalizing or codifying what you could be doing in jGRASP interactions to make sure a method is working correctly. That is, the sequence of statements that you would enter in interactions to test a method should be entered into a single test method. You should have at least one test method for each method in RingTorus, except for associated getters and setters which can be tested in the same method. In addition, you should have sufficient test methods so that each method, statement, and condition in RingTorus are covered. Collectively, these test methods are a set of test cases that can be invoked with a single click to test all the methods in your RingTorus class. Code and Test: A good strategy would be to begin by writing test methods for those methods in RingTorus that you “know” are correct. By doing this, you will be able to concentrate on the getting the test methods correct. That is, if the test method fails, it is most likely due to a defect in the test method itself rather the RingTorus method being testing. As you become more familiar with the process of writing test methods, you will be better prepared to write the test methods as new methods are developed. Be sure to call the RingTorus toString method in one of your test methods and assert something about the return value. If you do not want to use assertEquals, which would require the return value match the expected value exactly, you could use assertTrue and check that the return value contains the expected value. For example, for RingTorus ex3: Assert.assertTrue(ex3.toString().contains(“”Large Example””)); Also, remember that you can set a breakpoint in a JUnit test method and run the test file in Debug mode. Then, when you have an instance in the Debug tab, you can unfold it to see its values or you can open a canvas window and drag items from the Debug tab onto the canvas. You can also Project: RingTorus with JUnit Tests – Part 2 Page 6 of 6 Page 6 of 6 step-in to the method being called by the test method and then single-step through it, looking for the error. The Grading System When you submit RingTorus.java and RingTorusTest.java, the grading system will use the results of your test methods and their level of coverage of your source files as well as the results of our reference correctness tests to determine your grade. In this project, your test file should provide method, statement, and condition coverage. Each condition in your source file must be exercised both true and false. See the note below for hints on testing the equals. To see your code coverage in Web-CAT, on “Your Assignment Submission Results” page, in “File Details”, click on your source file and look for any highlighted lines of code. Hover your mouse on the highlighted source code, to see the hint about what was not covered. Example of hints you might see include: (1) This line was never executed by your tests. (2) Not all possibilities of this decision were tested. Remember that when you have N simple conditions combined, you must test all N+1 possibilities. Note For Testing the equals Method Perhaps the most complicated method to test is the equals method in RingTorus. This method has three conditions in the boolean expression that are &&’d. Since Java (and most other languages) uses short-cut logic, if the first condition in an && is false, the &&’d expression is false. This means that to test the second condition, the first conditions must be true. Furthermore, to test the third conditions both the first and second conditions must be true. To have condition coverage for the equals method, you need the four test cases where the three conditions evaluate to the following, where T is true, F is false, and X is don’t care (could be true or false): FXX – returns false TFX – returns false TTF – returns false TTT – returns true

$25.00 View