QuestionQuestion

Transcribed TextTranscribed Text

Overview: The class you’ll implement is for a Dam (a large structure for storing water, not any other meaning ;-). If it helps, you can conceptually model a Dam as a bathtub or a sink: just a big container for water. Water flows in, water flows out, and the net difference between the two is stored (or drained). A Dam is conceptually no different from a bathtub: it just uses vastly bigger numbers, and different units of measurement. Given the upcoming rainy season, and the past Oroville Dam emergency, this class seems particularly “real-world”. We’ll (eventually) want to know things about any Dam for a “Dam health report”, like: Is it filling, draining, or holding steady? How full is it now? (percentage-wise) At current rates, on what date will it empty completely? (or with an El Nino winter, overflow?) What happens to storage if we import or release some more water? You will also extend your UtilsFL class for user inputs, by adding methods to read double and String data. These should just be modified clones of your existing methods for ints and chars, respectively. Your main() client program or Dam class should no longer have any need to use Scanner or JOptionPane directly. Java Objectives: 1)Creation of a new user-written Java class [CSLO-2] 2)Designing a new class using pseudocode and method stubs [CSLO-3] 3)Application of Java to model and solve real-world scenarios [CSLO-4] 4)Java instance variables [CSLO-2] 5)Java constructors, default and full [CSLO-2] 6)Java display methods, toString() and print() [CSLO-2] 7)Java accessors and mutators [CSLO-2] 8)Java object equivalence [CSLO-2] 9)Method overriding versus method overloading [CSLO-2] 10)Code reuse using existing and new data prompt methods [CSLO-3] 11)Incremental development and unit testing for a larger class [CSLO-3] Background: First of all, here is the genesis for this assignment. This is a water storage table which (used to) appear daily on the weather page of the Sacramento Bee. DATE of the data readings at left: 04/28/15 YEAR each dam was completed: Folsom: 1956 Oroville: 1968 Shasta: 1945 Nimbus: 1955 1 acre-foot  43,560 cubic feet YOU WILL NEED DATA SIMILAR TO THIS NEXT WEEK TO TEST NUMERCAL ACCURACY OF YOUR PROGRAM. You do NOT need any of this data THIS week! Here is a link to actual, current state water data such as this: http://cdec.water.ca.gov/cgi-progs/current/RES Here is a simplified physical model of a Dam. A DAM is just a huge earthen or concrete structure for storing snowmelt and other runoff for all state water needs. You can think of it as a very large bathtub. Capacity is how much the dam can possibly hold. Storage is how much the dam holds at any point in time. The net difference between inflow and outflow, accumulated over time, tells us whether our Dam is filling or emptying, and how fast. Capacity stays constant, but the storage fluctuates with inflow and outflow. Can you map the numbers in the newspaper clipping above, to the model above? Can you identify the 5 instance variables (columns) in the clipping on the above left, and the other 2 in the pane on the above right? Do you also see a units conversion constant we’ll need to use later on? Preliminaries: 1)As always, begin by FIRST reviewing all the weekly lecture materials, videos, and source codeexamples. Review the weekly office hour recording when it becomes available. These thingsshould answer most, if not all, questions. If anything is still cloudy in your mind, please ask! 2)For this specific assignment, it’s important that you first view ALL the code walk-thrus whichdemonstrate the step-by-step creation of another class. Follow along with them if you want to,while creating your own class. THE PROCESS DEMONSTRATED THERE IS EXACTLY WHAT I WANTYOU TO FOLLOW IN CREATING THIS CLASS! This program may be lengthy and tedious, but if you break it down as demonstrated, it is notdifficult. I want you to experience first-hand why we prefer to use classes that have already beenbuilt by someone else! 3)Begin by creating the file DamFL.java. Use your template as a starting point. Don’t forget toupdate the comment block accordingly. 4)For this Dam class, keep in mind that you will have a main() method, but now it should appear atthe end of your class file, and its purpose is to contain test code for the class code above it. 5)Have the provided Dam class API available. This will be your roadmap for the class you are creating.A class such as this one is a collection of a small handful of data, plus LOTS of methods whichoperate upon/with that data. Also have on hand the sample test code outputs. 6)For this program, it will be helpful to be able to view the class code at the top, at the same time asthe main() method test code at the bottom. Use the “split” options in jGRASP : View  Split View 7)After you have implemented the readDouble() and readString() methods in your Utils, please addthe following code exactly as shown to your Utils file: You can add this code NOW, but comment it out until your readString() is created. Then use this pause() method in your test code to “slow down”, or “throttle”, the scrolling of your outputs. Requirements: Create a DamFL class which meets the following requirements. The intended API for the class is given in an accompanying document. All of the needed instance variables and methods are given there. 1.API: A Dam API document will be separately published. a.Your class MUST strictly adhere to the methods listed in the API b.I will use a test program to grade your class, so it MUST strictly adhere to the API! c.The test program used will be the one which generated the provided sample outputs. 2.Input/Output: Add the following methods to your existing UtilsFL class a.A readDouble() method: prompt the user for an input double value, using either commandline or popup GUI modes. i.Clone and modify this from existing readInt() ii.Provide type-safe handling. b.A readString() method: prompt the user for an input String value, using either commandline or popup GUI modes. i.Clone and modify this from existing readChar(), except return the entire string. ii.No type-safe handling is needed, any text entered is automatically a String. c.Add the pause() method shown on the preceding page. Use this to throttle your output. d.There should be NO direct usage of Scanner or JOptionPane in your Dam class. 3.Instance variables (7): Provide instance variables for the 5 quantities seen in the newspaper imageabove, plus the 2 other ones on the right side. a.All instance data must be private. b.Use the namings exactly as shown in the API, your class must run against the test program. c.Use doubles for all 4 water-related quantities. i.Name of the dam [String] ii.Year the dam was opened (just the year) [int] iii.Current water storage [acre-ft] iv.Maximum water capacity [acre-ft] v.Water inflow rate [cu-ft/sec, or cfs] vi.Water outflow rate [cu-ft/sec, or cfs] vii.Measurement date of the current water data, as a [CS12Date] 4.Constructors (4): Provide the following 4 overloaded constructors versions: a.Default constructor: for ease of grading, use the following recognizable default values: i.Name:<default dam> ii.Year:1900 iii.Water data:0.0 for all iv.Date of data: use today’s date, either today() or default CS12Date b.Full constructor: allow user specification of all 7 instance variables c.Alternate constructor: just the dam name and its opening year (above defaults for allother values) d.Alternate constructor: just the dam name and capacity (above defaults for other all values) 5.Display methods (3): Provide the 3 following display methods: a.Override the toString() method, to display all instance variables, using a comma-separatedformat as shown in lecture examples. b.print(), to display just all instance variables, in a multi-line labeled format, & display UNITS c.An overloaded print(), which also prints an input text message header d.Don’t worry about any fancy data formatting this week. We’ll add that next week. 6.Accessors/mutators (3x7): Provide 3 methods for each instance variable. Use standard naming: a.An accessor for EACH instance variable b.A mutator for EACH instance variable c.An overloaded mutator for EACH instance variable, which will prompt the user for its value. i.Either a command line or popup GUI input mode should be allowed. ii.For ease of grading/testing, please use the command line input mode exclusively inyour test code. 7.Equality: Override the equals() method to compare instances of DamFL objects. a.The method should adhere to the standard interface b.The method should be able to accept ANY object for comparison. 8.Testing: Test your DamFL class in two ways: a.Add a main() method at the end of your class. Add some basic test code to test your classas you implement each feature. See the lecture materials for what this might look like. i.Test all 4 constructors by creating a DamFL object with each one. ii.Display each of the 4 created objects, using both its (implicit) toString() and theoverloaded (messaging) print() method. 1.Pick ONE of the created objects, and test the other methods upon it. Youdo NOT have to test ALL methods on ALL the objects. iii.Test all mutators using the prompting mutators, which internally use the “plain”mutators. iv.Test all the accessor methods. v.Test the equality method 1.Test one Dam against itself (should be true) 2.Test one Dam against any other Dam (should be false) 3.Test one Dam against some other type of object (should be false) vi.Practice “before and after” testing as appropriate: display an object “before”,make some changes, display the object changes “after”. vii.Make liberal use of pause() to slow down the spewing of your test outputs. viii.Clearly annotate (label) all outputs as to what they represent. The overloaded(messaging) version of print() is useful for this. b.Run your class against the provided test code. i.Download test code file DamTest1RL.java. Review the instructions in the header. ii.In jGRASP, do a global substitute from UtilsRLUtilsFL, and save the changes. iii.Compile the test code. This will check your adherence to the Dam API. iv.Run the test code. Carefully inspect all results, make any changes needed. v.I will run this test code against your Dam class, so make sure it runs w/o errors! Structure: Below is the structure of your program. The new DamFL class represents the bulk of all the new code. Create new methods in your supporting utilities class as shown. Your program will be executed from the required main() method unit test code of the new DamFL class. Here, main() is actually in a subordinate role within the DamFL class, as indicated by its placement at the end, but it is still needed to exercise your newly-written class. You will also need to run your DamFL class against the provided DamTest1RL test code as a check. Design Suggestions: Make sure you watch the weekly office recording, where we’ll talk thru this program. First, orient yourself by reviewing the items shown in the Preliminaries section above. Next, review the Requirements and the DamFL API document, which closely mirror each other. Review the class creation approach outlined in the “Writing Classes” lecture materials and videolectures. You should be able to implement most of this program by following the proceduresdemonstrated in the lecture notes and code walk-thru videos! Begin with a pseudocode outline of the new class. Take an incremental approach: Build a little, testa little, repeat. DO NOT try and implement the entire class from top to bottom in the API! This is NOT a hardprogram to write, if you break it into small pieces (lots of individual methods)! It may be long andtedious, but it is NOT difficult. Write your test code bit by bit, as you implement your class in the methods order demonstrated.This will help you find any errors much faster, than all at the very end. Suggested Implementation: First, make any needed updates to the various data read methods, based upon any prior rubricfeedback. Update any indents, nesting, layout, etc. Next, implement the required readDouble() and readString() in your Utils class. These should eachbe slightly modified clones of what you already have. Start by implementing all the code for ONE instance variable (designer’s choice of which one). oDeclare ONE instance variable and its two default and full constructors. oImplement the 3 display methods for the ONE instance variable. oCreate your main() unit test code method at the bottom, and test the two constructors bycreating objects and displaying them. oImplement the accessor and mutator trio. Test them in your unit test code. oImplement the equals() method. Test it in your unit test code. Once all the above is working for ONE instance variable, implementing the other 6 instancevariables, one at a time, becomes trivial. Most of the added code at this point should be copy-and-paste with some simple modifications. oAlso, add the two additional constructors. oTest your added methods as you go along, in your unit test code. Make sure to comment your code well. oMake sure to adequately comment all program logic AND your test code. oAt a bare minimum, precede EACH method with a one-line comment summarizing itspurpose. When you think your class is complete, its final check is to run it against the provided test code. oDo a global replace of DamRL  DamFL (your initials). oYour Dam class must compile and run successfully against the test code! oInspect the outputs (or any errors) carefully, and make any updates needed. Testing Suggestions: The best approach when creating a large class such as this one is to write simple test code as you go along. That way, you’ll know right away if the changes you’ve made work properly or not. Once you have the test code written for the first instance variable, most of the remaining test code is just simple copy-and-paste, with edits. You may use the provided test program for ideas as to how to write your own main() method test code, but you may NOT simply copy-paste it into your main() method. Don’t simply copy and adapt the example Person class test code either. I CAN TELL THE DIFFERENCE! Write your own test code from scratch and incrementally as you develop the methods of your class. Be sure to both comment your test code and annotate your output, so the reader clearly understands what output corresponds to which test code. Make liberal use of the provided pause() method in your test code. It will prevent your output from “screaming past”, and allow you to closely examine your outputs. Put pauses in between all logical groupings of your test code. A good testing strategy to follow is generally: create an object, display it “before”, make some change to it, display it “after”. Make sure the changes behave as you expect them to. Inspect your results carefully. Be sure you briefly test ALL the following in your main() method test code: All 4 constructor forms Both display methods, toString() and print() All accessors and mutators (3 per instance variable). Remember that the prompting form internallytests the other form. The equals() method: compare two different Dam objects, an object against itself, and a Damobject against some non-Dam object (a String? a CS12Date?) Finally, you don’t have to test each of your methods against EVERY Dam object. Just one object issufficient. I will run your Dam class using the provided test program, which generated the sample outputs, to check that all required methods are implemented per the published API. Make sure that your Dam class method naming adheres strictly to the published API! Sample output: See the sample program output given in a separate file. Your test code should resemble this, but you can format or label it as you wish. Your output does NOT have to match exactly, but make sure all the same methods are checked, in roughly the same order.

Solution PreviewSolution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

import java.util.Scanner;
import javax.swing.JOptionPane;

public class UtilsFL {

    //---------------------------------------------------------------------------
    // user input methods, by datatype
    //---------------------------------------------------------------------------
    // get an int value
    public static int readInt(String prompt, boolean guiMode) {
       // set up data and objects
       Scanner input;
       int data = 0;
       boolean failed = true;

       input = new Scanner(System.in);
       /**
         * Add type-safe checking for both input modes, such that your method
         * loops endlessly until a valid int value is read.
         */
       while (failed) {

            /**
             * Type-safe checking for JOptionPane requires exceptions: see the
             * example code given for both modes in the “looping while type
             * safe” materials. Use the exceptions code almost exactly as-shown.
             */
            try {
                //--------------------------
                // prompt for an input int value using Scanner mode, for "false" case
                if (guiMode == false) {
                   System.out.print(prompt);
                   //Type-safe input handling [CSLO-4]
                   data = Integer.parseInt(input.next());
                } // create the equivalent "else" steps using JOptionPane mode, for "true" case
                else {
                   // get input
                   String str = JOptionPane.showInputDialog(null, prompt).trim();
                   // convert it to integer
                   //Type-safe input handling [CSLO-4]
                   data = Integer.parseInt(str);
                }
                /**
                * Handling of non-integer inputs with reprompting (in readInt)
                */
                failed = false;
            } catch (Exception e) {
            }
       }

       //--------------------------
       return data; // regardless of whether obtained by Scanner or JOptionPane
    }

    /**
    * readChar() method to obtain single-character inputs
    *
    * @param prompt
    * @param guiMode
    * @return
    */
    public static char readChar(String prompt, boolean guiMode) {
       // set up data and objects
       Scanner input;
       String data = "";
       boolean failed = true;

       /**
         * Assume you do NOT need to guard against 0-length input, but it’s a
         * nice check to add if you want to.
         */
       while (data.length() == 0) {
            //--------------------------
            // prompt for an input int value using Scanner mode, for "false" case
            if (guiMode == false) {
                input = new Scanner(System.in);
                System.out.print(prompt);
                data = input.next();
            } // create the equivalent "else" steps using JOptionPane mode, for "true" case
            else {
                data = JOptionPane.showInputDialog(null, prompt);
            }
       }
       //--------------------------
       // Type-safe checking is not needed

       return data.charAt(0);
    }...

By purchasing this solution you'll be able to access the following files:
Solution.zip.

$64.00
for this solution

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Java Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Decision:
Upload a file
Continue without uploading

SUBMIT YOUR HOMEWORK
We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats