CS1083讲解 、辅导 Java编程语言
Module 2 Assignment
Worth 2% of your total course grade
CS1083 – Introduction to Computer Programming II (in Java)
Online Open Entry Version
Instructor: Andrew McAllister
Assignment Objectives
The purpose of this assignment is to give you practice:
• applying the linear search algorithm to a realistic problem
• working with one-dimensional arrays
• working with Java objects, including a "has a" relationship
• generating pseudo-random numbers
• using an incremental development approach
General Instructions for All Assignments
• Follow the instructions in the document "Java Coding Guidelines.pdf" available
within the "Start Here" module, under the "Assignments" topic.
• For each .java file you create, include a javadoc comment (one that begins with
/**) at the beginning of the file that describes that Java class. This comment block
should include a line that begins with @author followed by your name and
student number on the same line. (Note: inclusion of this comment is part of the
instructions given in "Java Coding Guidelines.pdf")
• Include comments throughout your programs to explain any non-obvious portions
of your code.
• It is recommended that you create a separate folder on your computer for each
assignment. You might even wish to create separate sub-folders within an
assignment folder if the assignment has multiple parts. Keeping your work
organized makes it easier to find things later when you want to review what you
have done.
Assignment Guide
• Few things in life are more frustrating than losing your work while working on an
assignment. Get in the habit of saving frequently when working on an
assignment. Also, regularly make backup copies of any files you create as part of
your work for this course.
• Feel free to email your instructor if you need help in completing an assignment.
When you do so, please attach to the email a copy of *all* files required to
compile and run the program you are asking about, even if you downloaded
those files from D2L. (Otherwise the instructor will have to figure out what files
are missing and then go looking for them. Make it convenient to help you.) Also
describe the problem you are encountering and the specific help you would like
to receive.
• Submitting your assignment involves creating a pdf file and uploading that single
file to the assignment drop box on D2L. In general, that file will tend to include all
Java code you wrote for the assignment, plus any output from running your
programs that the assignment instructions specify you should capture. Specific
submission instructions are included at the end of each assignment.
• To create the pdf file for each assignment, begin by opening a new document
using the word processing program of your choice. Save the document using the
name “Your Name CS1083 Module x Assignment Submission.docx” Replace x
with the correct module number. “docx” may be different depending on which
word processing software you choose to use.
• If you don’t already have a word processor, UNB students are able to use
Microsoft Office 365 (includes Microsoft Word) for free, which can be accessed
by logging in to MyUNB.
• At the beginning of your submission document enter your name, your student
number, CS1083, the assignment name (this one is “Module 2 Assignment”), and
the date. It doesn’t matter if the date is when you started working on the
assignment or when you submit it – either will do.
• You can add content to your submission document as you work on the various
questions in the assignment. Clearly label each part of the assignment (“Part A”
etc.) in your document. Be sure to save frequently as you work on this document.
• When your document is complete, save / export it as a pdf file. Always make sure
your pdf file opens properly before uploading it.
• To include Java code in your submission document, copy all the text in your .java
file and then paste that text into your submission document. Use a monospaced
font (e.g.: Consolas , Courier ) for your code to maintain proper indentation.
Submitting code without proper indentation will result in marks being deducted.
It’s not enough that your code is indented in your text editor or in your integrated
programming environment – the indentation must show up that way in your
submission document as well. This sort of thing is part of learning to be an IT
professional.
• To include output from running your program in your submission document, the
preferred method is to copy and paste the text from your command prompt
window. Include the line with the “java” command you used to run your program.
If the text shows up as a weird font or colour in your submission document,
first paste the text into a blank text editor document, then copy and paste from
there into your Microsoft Word submission document. This will remove all
formatting from the text.
Use a monospaced font (e.g.: Consolas , Courier ) for output text in your
Word document. This will maintain alignment of your output.
• If at all possible, each line of code and each line of output should appear on a
single line in your submission document. Avoid allowing lines to “wrap” around
onto the next line. Use the tips provided in the “Avoiding Wrapped Lines” section
on the next page to accomplish this.
• To copy text from your command prompt window, try selecting the desired text
and then pressing either command-c (Mac) or control-c (Windows or Linux). If
you have issues, you can always use Google to see how to do this on your
specific type of computer.
• If a program involves graphical output (such as a JavaFX GUI program), capture
a screen shot of the output and include that as a picture / image in your
submission document.
Make sure the image includes only the relevant portion of the screen (such
as a GUI window). Capturing an image of your entire computer screen often
makes the relevant portion too small to see, with tiny text that is difficult to read.
This makes your assignment submission difficult to grade.
• To capture a screen shot of a selected portion of your screen, try command-shift4 (Mac), WindowsKey-shift-s (Windows), or shift-PrtScrn (Linux).
Avoiding Wrapped Lines
In the following example, the lines of code containing the comment and the println
statement are both too long. The text is formatted so those lines can't fit all on one line
in this document. This obscures the indentation and makes the code more difficult to
read.
import java.util.Scanner;
public class WrapExample
{ public static void main(String[] args)
{ double pay = hours * wage;
int dollars = (int) pay;
int pennies = (int) ((pay - dollars) * 100.0);
// First all * and / operations are performed, left to
right, then all + and - operations, left to right
System.out.println("\nThe pay for " + name + " is " +
dollars + " dollars and " + pennies + " cents.\n");
} // end main method
} // end class
Below is the same code, but reformatted so none of the statements wrap around onto
the next line. Several changes were made:
1. The font size (in the Word document) is changed to a smaller size,
2. The tab size (in the Word document) is reduced
3. The longer statements and long comments are broken up onto multiple lines (do
this in your text editor, in the .java file), and
4. If need be, you can change the orientation of your Word document from Portrait
to Landscape
Now the indentation of the code within the main method is easier to see.
import java.util.Scanner;
public class WrapExample
{ public static void main(String[] args)
{ double pay = hours * wage;
int dollars = (int) pay;
int pennies = (int) ((pay - dollars) * 100.0);
// First all * and / operations are performed, left to right
// Then all + and - operations, left to right
System.out.println("\nThe pay for " + name + " is " + dollars
+ " dollars and " + pennies + " cents.\n");
} // end main method
} // end class
Before You Begin…
Two important notes:
1. This assignment is to be completed in multiple parts, with an incremental
development approach. It is important that you read the entire assignment before
you begin programming.
2. Make sure you keep the work you do on this assignment. You will need it for
upcoming assignments later in this course.
Instructions – The RoomSchedule Class
Write a Java program that simulates managing reservations for hotel rooms.
Your program will keep a separate schedule for each room in a hotel by coding a
RoomSchedule class. A RoomSchedule object contains the following information:
Use Java’s built-in LocalDate class for all date values in your program, including the
startDate value shown above.
A RoomSchedule is for one room, which has a room number. The schedule has a given
start date and extends for a given number of nights (represented by the instance
variable scheduleLength). The RoomSchedule constructor uses scheduleLength to
create a “schedule” array, which stores that quantity of int values. The example shown
above has a schedule for only seven nights; a more realistic example might be to create
a schedule for, say, the next year or more, in which case scheduleLength might be
given as 365, or even longer. To keep things simple, we’ll stick with short schedules for
this assignment.
Each value in the array represents whether or not the room is reserved for a specific
night. The first array element (index 0) represents the night of the start date. Array
element 1 represents the following night, and so on. In the example shown above, the
array element with index 2 represents whether room 213 is reserved for the night of
December 18th
.
No date values are stored in the array. Instead, the date for any given night can be
calculated using the start date and the index of the array element associated with that
night. (I show you how to do that calculation a little later in this document.)
A reservation books a specific room, where someone is scheduled to arrive at the hotel
and check in on a specific date and to stay for a given number of nights. Each
reservation also has a unique reservation number. We’ll use 4-digit reservation numbers
for this assignment. (Notice we do not record any information about hotel guests.)
For example, suppose we reserve room number 213 for someone to check in on
December 16th and stay for three nights. Assume we assign reservation number 1000 to
this booking. Making this reservation would change the state of the example
RoomSchedule object to the following:
This signifies that someone has reserved room 213 with the intention to check in on
December 16th, stay for three nights (the 16th, 17th, and 18th), and check out the morning
of December 19th
. The remaining nights in the schedule (from December 19th onward)
are still available for other reservations. The value 0 is used to represent “available”.
Pro tip: Your code will be more readable if you create a constant called AVAILABLE
containing the number 0, and use that constant in your code wherever 0 means
“available”.
Let’s try making reservation number 1001, checking in on December 21st and staying
two nights. We end up with this schedule:
By the way, if reservation number 1001 was for three or more nights, then we would be
attempting to go beyond the last day in the schedule. Such a reservation would not
succeed; no change would be made to the schedule array. The same would be true if
we attempt any reservation that includes any nights before the start of the schedule or
that are already reserved.
For example, suppose we attempt to make reservation number 1002 for the night of
December 17th. We can see in the schedule that this overlaps with reservation number
100, and thus the schedule for room 213 would not be changed.
But let’s suppose reservation number 1000 is canceled. This changes the schedule for
room 213 to the following:
Now we could make reservation 1002 and end up with this schedule:
So far, you’ve seen the effect of two methods for the RoomSchedule class:
makeReservation and cancelReservation.
makeReservation either (a) successfully adds a reservation to the schedule and returns
true (indicating the reservation was made), or (b) finds the reservation cannot be made
and returns false.
cancelReservation either (a) successfully removes a reservation from the schedule and
returns true (indicating the cancellation succeeded), or (b) finds that the given
reservation number is not in the schedule for this room and returns false (indicating the
cancellation did not succeed).
We also want to be able to confirm a reservation. Given a reservation number, perform
a sequential search of the schedule array to see if that reservation exists for this room.
If found, that method should return the:
• reservation number
• room number
• check in date
• check out date
“But hold on,” you might say, “a Java method can only return one value. How can the
confirmReservation method return all the information you just listed?”
Well, isn’t Java an object-oriented programming language? The confirmReservation
method returns an object containing those four values, which means you need to code a
Java class to enable this. I suggest Reservation as the name of this class.
If a given reservation number is not found in this room’s schedule, then the
confirmReservation method returns null.
Also include a toString method in the RoomSchedule class. For the most recent
schedule status shown above, toString() should produce a String value similar to the
following:
Schedule for room #: 213
========================
2023-12-16 0
2023-12-17 1002
2023-12-18 0
2023-12-19 0
2023-12-20 0
2023-12-21 1001
2023-12-22 1001
========================
Also include a method called conciseString in your RoomSchedule class, which for the
most recent schedule status shown above should produce a String value that can be
displayed on one line, similar to the following:
213 -*---**
This conciseString output includes the room number (in this case 213), to the right of
which appears the same number of dashes (-) and asterisks (*) as there are nights in
the schedule. A dash indicates a night that is available; an asterisk indicates a night that
is reserved. The conciseString output shown above includes one asterisk for reservation
number 1002, and two asterisks because of reservation number 1001.
Instructions – LocalDate
As mentioned above, you are to use Java’s LocalDate class for representing all date
values for this assignment.
You can find documentation on the LocalDate class here. A Google search with a
phrase like “Java LocalDate tutorial” will provide you with examples of using this class.
Here are the LocalDate capabilities you are likely to need for this assignment:
• Importing two required classes:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
• Creating a LocalDate value that is some number of days (an int value) after a
given LocalDate value:
givenDate.plusDays(someNumberOfDays)
• Checking whether one LocalDate value is before another. This returns a boolean
result:
oneDate.isBefore(anotherDate)
• Checking whether one LocalDate value is after another. This returns a boolean
result:
oneDate.isAfter(anotherDate)
• Calculating how many days are between two dates:
int index = (int) startDate.until(checkInDate, ChronoUnit.DAYS);
• Converting a LocalDate value to a String so it can be displayed, or so it can be
concatenated with another String. This produces a String in the default format
"2023-12-16":
someDate.toString()
• Creating a LocalDate object for the current date:
LocalDate.now()
Instructions – The HotelSchedule Class
Write a HotelSchedule class that simulates managing reservations for several rooms in
a hotel.
The HotelSchedule constructor accepts these three parameters:
• The quantity of rooms
• The start date for the schedule
• The number of nights in the schedule (scheduleLength)
Based on those three values, the constructor creates an object you can envision as
follows:
The “rooms” instance variable is an array of RoomSchedule objects. The length of this
array is given by roomQuantity.
Each RoomSchedule object is given the same startDate and scheduleLength.
Use Java’s Random class to help generate a pseudo random room number to pass in
each time the HotelSchedule constructor invokes the RoomSchedule constructor.
Assume the hotel has three floors and at most twenty rooms on each floor. That means
the room numbers you generate must be in the range 101-120, 201-220, or 301-320.
The code you write to generate a room number must make any one of those sixty
values equally likely.
Furthermore, each time you generate a possible room number for a particular element
in your “rooms” array, your code must make sure you have not already assigned the
same number to another room in the array. There must be no duplicate room numbers.
As you can see from the example on the preceding page, this approach will assign
room numbers in a jumbled order. This is on purpose. An upcoming assignment
involves writing code to sort the rooms in order. For now, leave them in the jumbled
order.
Your HotelSchedule class will support the same three tasks as your RoomSchedule
class:
• Make a reservation
• Cancel a reservation
• Confirm a reservation
Each of those three HotelSchedule methods uses the RoomSchedule method of the
same name to help accomplish the task.
For example, the HotelSchedule makeReservation method accepts a check in date,
number of nights, and reservation number … which happens to be exactly the same
information required by the makeReservation method in the RoomSchedule class.
The HotelSchedule makeReservation method performs a sequential search beginning
with the first room in the array. Call the makeReservation method for that room and
capture the boolean result. Keep looping through the rooms as long as you haven’t
checked all the rooms yet and no room reports a successful reservation. Once the
reservation is made, do not continue looping through the rest of the rooms.
The HotelSchedule makeReservation method returns true if the reservation succeeded
with one of the rooms, or false if you went through all the rooms and every reservation
attempt failed.
The HotelSchedule cancelReservation and confirmReservation methods follow
essentially the same algorithm as makeReservation, except of course
confirmReservation returns a Reservation object rather than a boolean result. You will
find that your code for these three methods is very similar.
To help with testing, include a getRoomSchedule method in your HotelSchedule class.
Given an array index, this method returns a pointer to the corresponding
RoomSchedule object from the “rooms” array.
Also include a toString method in HotelSchedule. This method uses the conciseString
method from the RoomSchedule class to help produce a result similar to the following:
Rm# Reservations
=== ============
213 ***-**-
109 --****-
306 -------
102 -------
214 -------
=== ============
This display is consistent with the five RoomSchedule objects shown on a previous
page as part of a HotelSchedule object, only after a few reservations have been made.
Recall that the start date for this hotel schedule is December 16th
, 2023. Assume we
start with no reservations, and we attempt to make a first reservation beginning on the
16th for three nights. Your code should loop through the rooms, attempting to make the
reservation with each one, starting with room 213. Since the entire schedule is
available, the reservation will be made in room 213, and no other rooms will be
checked. That three-night reservation is represented by the first three asterisks for room
213 in the display above.
Assume the second reservation attempt is to check in on the 18th and to stay four
nights. Again, your code will loop through all the rooms, starting with room 213. That
attempt will fail, because the first reservation already includes the 18th for room 213, so
your code will then call makeReservation for room 109. That attempt will succeed,
which is reflected by four asterisks in the display above.
Finally, suppose we attempt a third reservation with a check in on the 20th, staying two
nights. Room 213 has availability for those two nights, so that is where the reservation
is made.
Instructions – Sequential Search Hints
This assignment requires you to use a sequential search algorithm as part of several
different tasks. For example, when making a reservation in the RoomSchedule class,
you must search through the requested nights to see if they are all available. When
making a reservation in the HotelSchedule class, you must search through the rooms to
see if a room succeeds in making the reservation.
Sequential searches are also required for the cancel and confirm operations.
These searches share a similar characteristic; the search should stop when the desired
result is found. For example, the makeReservation operation should not continue after a
reservation has been made. The cancelReservation operation should not continue once
the specified reservation has been located and canceled.
A common coding mistake with this type of operation is to write a “for” loop that iterates
through the entire array. Instead, I recommend you use a “while” loop that stops when
the desired result has been achieved.
A common coding pattern to achieve this is as follows:
int i = startingIndex; // Often this is 0, but not always
boolean done = false;
while (i < arraySize && !done)
{ if ( /*you find what you are searching for*/ )
done = true;
else
i++;
}
// Often what you do here will depend on what kicked you out of
// the loop. You can use i and done to determine this.
You will likely use some variation of this coding pattern multiple times in completing this
assignment.
Instructions – Incremental Development
I often receive emails from students whose code compiles but there is an error when
attempting to run the program. Either the program crashes or produces an unexpected
result. This type of error can be difficult to find, especially with an assignment like this
one that involves a fair amount of code … and especially when a student writes all the
code for an entire assignment and only then tries to run and debug the program.
The problem with that strategy is that it can be difficult to know what code might be
causing the issue.
To help with this, I encourage incremental development, where you code a little, test a
little, code a little, test a little, and so on. This can save you so much time and so many
headaches. The advantage is that when an error occurs, it’s almost certain to be in the
little bit of code you just wrote. It’s much easier to locate any problems in your code.
This assignment forces you to use incremental development by splitting the work into
six parts, as described below.
Part A
For the RoomSchedule class, code just the following:
• Instance variables
• Constructor
• toString() method
Write a test class that creates a RoomSchedule office starting with the current date (use
the “now” method), with a schedule length of two weeks. Use the toString() method to
display this schedule. All dates should show as 0, meaning available.
Create a clearly labeled “Part A” section in your submission document. Include in this
section:
• The source code for both classes
• The output from running your testing code
Part B
Add a makeReservation method to the RoomSchedule class.
Add to your test class:
• Two calls to makeReservation that succeed
• One call to makeReservation that fails because at least one of the requested
dates is before the start of the schedule
• One call to makeReservation that fails because at least one of the requested
dates is after the end of the schedule
• One call to makeReservation that fails because at least one of the requested
dates overlaps with an existing reservation
Embed each makeReservation call within an if condition, and display an appropriate
message depending on whether the reservation succeeds. Each message should
include sufficient information so the meaning of each test case output is clear.
Use the toString() method a second time to display the schedule after reservations have
been made.
Create a clearly labeled “Part B” section in your submission document. (Each section
should start on a new page.) Include in this section:
• The updated source code for both classes
• The output from running your testing code
Part C
Add the cancelReservation and conciseString methods to the RoomSchedule class
Add to your test class:
• One call to cancelReservation that succeeds
• One call to cancelReservation that fails
Embed each cancelReservation call within an if condition, and display an appropriate
message depending on whether the cancellation succeeds. Each message should
include sufficient information so the meaning of each test case output is clear.
Use the toString() method a third time to display the schedule after cancellations have
been made. Also call the conciseString() method so you can see that the two outputs
are consistent.
Create a clearly labeled “Part C” section in your submission document. Include in this
section:
• The updated source code for both classes
• The output from running your testing code
Part D
Add a confirmReservation method to the RoomSchedule class. Also write the
Reservation class, which is necessary for confirmReservation to work.
Add to your test class:
• One call to confirmReservation that succeeds in returning a Reservation object
• One call to confirmReservation that returns null
Embed each confirmReservation call within an if condition, and display appropriate
information so the outcome of each test case. When a Reservation object is returned,
call the toString method from that class to show the test result.
Create a clearly labeled “Part D” section in your submission document. Include in this
section:
• The source code for all three classes
• The output from running your testing code
Part E
Begin writing the HotelSchedule class with just the following functionality:
• The ability to construct a HotelSchedule object with unique, randomly assigned
room numbers
• A toString() method
Create a new test class that only does the following:
• Creates a HotelSchedule object with 10 rooms, today’s date as the start date,
and a schedule that is two weeks long
• Calls toString() to display this HotelSchedule.
Create a clearly labeled “Part E” section in your submission document. Include in this
section:
• The source code for HotelSchedule and your new test class
• The output from running your new testing code. You should see that all 14 nights
for all 10 rooms show as available.
Part F
Add all remaining functionality as described earlier in the document. Add to your new
test class appropriate testing code for this newly added functionality.
Create a clearly labeled “Part F” section in your submission document. Include in this
section:
• The source code for all classes
• The output from running your testing code.
Submission Instructions
Include the following in your submission document:
Your name, student number, CS1083, Module 2 Assignment, and the date.
Complete source code and testing output for each of Sections A through F as
described above.
D2L DROPBOX SUBMISSION INSTRUCTIONS
Upload only one pdf file to D2L. Do not upload separate files (such as your .java
files) as they will be ignored. Upload your submission document as follows:
1. In the top-navigation bar on the course screen, select 'Assessments' and then
'Assignments'.
2. Select the assignment title and follow the instructions to upload your submission
document.