CS 1110/1111 - Spring 2015 - Previous POTDs

Important Links: Submit POTDs to the Automated Grading System and Join the TA Office Hour Queue

POTD 19 - Particle.java - Due: Friday, April 10, 11:00 AM

We are now going to write a class to represent a Particle - a physical object that can move around the screen; it has mass, position, and velocity. Please implement the following API in your class:

Particle
− x : double
− y : double
− vx : double
− vy : double
− mass : double
+ Particle(x : double, y : double)
+ Particle(x : double, y : double, vx: double, vy: double)
+ Particle(x : double, y : double, vx: double, vy: double, mass : double)
+ getX() : double
+ getIntX() : int
+ setX(x : double) : void
+ getY() : double
+ getIntY() : int
+ setY(y : double) : void
+ applyForce(fx : double, fy : double, dt : double) : void
+ timePasses(dt : double) : void
+ getSpeed() : double
+ applyDrag(drag : double, dt : double) : void
+ bounceIfOutsideOf(r : Rectangle, bounciness : double) : void
+ toString() : String
Constructors

All three constructors should set each field of Particle to the given parameters or default values. The default values for vx and vy (which represent velocity) are 0, and for mass is 1.

getIntX() and getIntY()

These should return the value of x and y, respectively, cast as ints. This is useful because most of the drawing code in Java expects ints.

applyForce(double fx, double fy, double dt)

Apply the given force to calculate the change in velocities in the x- and y-directions. Consider the dynamics equations F = ma, and a = dv/dt, where dv means “change in velocity” and dt means “change in time”. Make sure to add the respective changes in velocity to the current values of vx and vy, don’t just set them equal to the change in velocity.

timePasses(double dt)

Adjust the x- and y-positions based on the respective velocities and the amount of time that has passed. Consider the dynamics equations v = dx/dt. Again, make sure to adjust the values of x and y, don’t just set them equal to the calculated dx and dy.

getSpeed()

Return the speed of the particle. Speed is a scalar value, so you should find the hypotenuse of the triangle that has vx and vy as its other two sides.

applyDrag(double drag, double dt)

Apply drag to the particle based on the given parameters. Keep in mind that drag is simply a special kind of force you can apply, so you should make use of other methods in this class. The force being applied in the x-direction is equal to -vx * speed * drag; it is similarly defined for the y-direction.

bounceIfOutsideOf(Rectangle r, double bounciness)

For this method, you should imagine you have a particle bouncing around inside a rectangle. This method is called when the particle is going to move outside the rectangle, and we want to bounce it off the interior wall to ensure it stays inside. There are four separate cases to consider:

  • If the particle is to the left of the left-most wall: set x equal to the x-coordinate of the left-most wall, and set vx equal to an always-positive value that is the product of vx and bounciness.
  • If the particle is to the right of the right-most wall: set x equal to the x-coordinate of the right-most wall, and set vx equal to an always-negative value that is the product of vx and bounciness.
  • If the particle is above the top-most wall: set y equal to the y-coordinate of the top-most wall, and set vy equal to an always-positive value that is the product of vy and bounciness.
  • If the particle is below the bottom-most wall: set y equal to the y-coordinate of the bottom-most wall, and set vy equal to an always-negative value that is the product of vy and bounciness.

Other things of note:

  • More than one of the above can occur simultaneously (specifically, one relating to x and one relating to y).
  • Remember that (0,0) is in the top-left corner, y-values increase going downwards, and x-values increase going rightwards.
toString()

The toString() method will return a string of the format “Particle at <x,y> with velocity <vx,vy> and mass m” The quotation marks in the examples just denote the beginning and end of the string - the string you return should not contain quotation marks. See the examples below.

Example
Example Usage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Particle p1 = new Particle(10.0, 20.0);
p1.toString();                      // should return "Particle at <10.0,20.0> with velocity <0.0,0.0> and mass 1.0"
Particle p2 = new Particle(10.0, 20.0, 2.0, 2.0);
p2.toString();                      // should return "Particle at <10.0,20.0> with velocity <2.0,2.0> and mass 1.0"
Particle p3 = new Particle(10.0, 20.0, 1.0, 3.0, 4.0);
p3.toString();                      // should return "Particle at <10.0,20.0> with velocity <1.0,3.0> and mass 4.0"
p2.timePasses(0.02);
p2.toString();                      // should return "Particle at <10.04,20.04> with velocity <2.0,2.0> and mass 1.0"
p2.applyForce(0, 9.8, 0.02);
p2.getSpeed();                      // should return 2.9702552078903928
p2.toString();                      // should return "Particle at <10.04,20.04> with velocity <2.0,2.196> and mass 1.0"
p2.applyDrag(0.1, 0.02);
p2.toString();                      // should return "Particle at <10.04,20.04> with velocity <1.9881189791684384,2.1829546391269457> and mass 1.0"
p2.bounceIfOutsideOf(new Rectangle(0,0, 10, 20), 0.5);
p2.toString();                      // should return "Particle at <10.0,20.0> with velocity <-0.9940594895842192,-1.0914773195634728> and mass 1.0"
Further Testing

You can also play around with Sparkles.java, a test class that demonstrates some of the uses of Particle. You can look through the code to see how the various methods are used, then run it to see the affects. Try adjusting some of the values passed into Particle’s method calls, and see how it affects the behavior.

Submission: Please submit Particle.java to the grading system.

POTD 18 - Scoreboard.java - Due: Wednesday, April 8, 11:00 AM

We are now going to write a class to represent a Scoreboard that keeps track of the score for both users in your Joust Game. Please implement the following API in your class:

Scoreboard
− score1 : int
− score2 : int
− gameOver : boolean
− highScores : ArrayList<Integer>
− highScoresCapacity : int
+ Scoreboard()
+ Scoreboard(highScoresCapacity : int)
+ incrementScore1() : void
+ incrementScore2() : void
+ getScore1() : int
+ getScore2() : int
+ isGameOver() : boolean
+ endGame() : void
+ getHighScores() : ArrayList<Integer>
+ addHighScore(int newScore) : void
+ loadHighScores(filename : String) : void
+ saveHighScores(filename : String) : void
+ toString() : String
Constructors

Both constructors should set score1 and score2 to 0, gameOver to false, and highScores to a new (empty) ArrayList<Integer>. The null (default) constructor should set highScoresCapacity to 3, and the specific constructor should set highScoresCapacity using the given parameter.

endGame

This method should set gameOver to true. You will use this in place of a setter.

addHighScore(int newScore)

This method should add newScore to highScores, in the appropriate location so that highScores remains sorted in decreasing order of scores. If there are now more than highScoresCapacity elements in highScores, remove the last element.

You might find some of the Collections class for sorting the list (note we want it in the reverse of Java’s default ascending order).

loadHighScores(String filename)

This method should perform the following steps:

  • Open the specified CSV file and add each value to highScores. The data will be presented as one line of CSV, with a comma separating each value. See the examples below.
  • Sort the values in highScores to ensure that the list is sorted in decreasing order.
  • If necessary, remove the lowest scores from the end of highScores until it contains at most highScoresCapacity elements. This method should include throws Exception in the header.
saveHighScores(String filename)

This method should write the current values in the highScores field to the specified filename, overwriting the file if it already exists. You should write the whole file in the same format as the files you read in loadHighScores - one line of CSV, with a comma separating each value. You should write the values in the order they appear in highScores. This method should include throws Exception in the header.

Scanners are used to read files; PrintWriters are used to write them. System.out is a PrintWriter, so you shoul be familiar with their basic use (generally print and println). One important thing to know: if you do not close() a PrintWriter after using it to write to a File, the writing might not actually happen.

toString()

The toString() method will return a string of the format “Score1 - Score2. Game (is/is not) over. High scores: (highScore1,highScore2,…)”. The quotation marks in the examples just denote the beginning and end of the string - the string you return should not contain quotation marks. You should not include parentheses around the words “is” or “is not”, nor around the high scores. See the examples below.

Example
Example Usage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Scoreboard sb = new Scoreboard();
sb.isGameOver();                     // should return false.
sb.getScore1();                          // should return 0.
sb.getScore2();                          // should return 0.
for (int i = 0; i < 7; ++i) {
  sb.incrementScore1();
}
sb.getScore1();                          // Should return 7.
sb.getScore2();                          // Should return 0.
sb.incrementScore2();
sb.addHighScore(sb.getScore1());
sb.addHighScore(sb.getScore2());
sb.saveHighScores("highScores.txt"); // Should write "7,1" to the file "highScores.txt"

Scoreboard sb2 = new Scoreboard(1);
sb2.toString();                          // Should return "0 - 0. Game is not over. High scores: ".
sb2.loadHighScores("highScores.txt");
sb2.getHighScores();                 // Should return a list containing [7].
sb2.endGame();
sb.isGameOver();                     // Should return false.
sb2.isGameOver();                        // Should return true.
sb.toString();                           // Should return "7 - 1. Game is not over. High scores: 7,1"
sb2.toString();                          // Should return "0 - 0. Game is over. High scores: 7".

Submission: Please submit Scoreboard.java to the grading system.

POTD 17 - CollisionBox.java - Due: Monday, April 6, 11:00 AM

This POTD can be used as a component in your Joust game - all the methods here can be useful for detecting and resolving collisions between moving objects, though you might not need to use them all in Joust.

Java has a built in rectangle class that has methods that tell you if two rectangles are intersecting, and can give you the intersecting rectangle of those two rectangles, shown below:

A B

In the image above, A.intersects(B) is true and A.intersection(B) is the green rectangle.

Please implement the following API in your class:

Collision Box
− rect : Rectangle
+ CollisionBox(Rectangle rect)
+ CollisionBox(x : int, y : int, width : int, height : int)
+ getRectangle() : Rectangle
+ collidesWith(other : CollisionBox) : boolean
+ moveTo(x : int, y : int) : void
+ moveCenterTo(x : int, y : int) : void
+ isHigherThan(other : CollisionBox) : boolean
+ isLeftOf(other : CollisionBox) : boolean
+ verticalDifference(other : CollisionBox) : int
+ horizontalDifference(other : CollisionBox) : int
+ isSmallerOverlapVertical(other : CollisionBox) : boolean
Constructors

Both constructors should initialize the rect field to an appropriate rectangle - either the parameter passed in, or a rectangle created from the parameters passed in.

collidesWith(CollisionBox other)

This method should return a boolean indicating whether or not this CollisionBox’s rectangle intersects with other’s rectangle.

moveTo(int x, int y)

This method should move the cornder of CollisionBox to the given parameters.

moveCenterTo(int x, int y)

This method should move the center of CollisionBox to the given parameters. If the CollisionBox has odd-number width or height, you may round either way.

isHigherThan(CollisionBox other)

This method should return a boolean indicating whether or not this CollisionBox is higher on the screen (smaller y) than other. Compare the center of the rectangles, not a corner.

isLeftOf(CollisionBox other)

This method should return a boolean indicating whether or not this CollisionBox is to the left of other on the screen (smaller x). Compare the center of the rectangles, not a corner.

verticalDifference(CollisionBox other)

This method should return the minimal y distance one of the two boxes would need to move in order for them not to overlap anymore. That will be the difference between the minimal y of one box and the maximal y of the other.

You may assume this method is only called on boxes that do overlap.

horizontalDifference(CollisionBox other)

This method should return the minimal x distance one of the two boxes would need to move in order for them not to overlap anymore. That will be the difference between the minimal x of one box and the maximal x of the other.

You may assume this method is only called on boxes that do overlap.

isSmallerOverlapVertical(CollisionBox other)

This method should return a boolean indicating whether or not the vertical difference between these two CollisionBox objects is smaller than the horizontal difference.

You may assume this method is only called on boxes that do overlap. A simple solution includes invoking the horizontalDifference and verticalDifference methods.

Example
Example Usage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CollisionBox box1 = new CollisionBox(new Rectangle(1, 1, 3, 3));
CollisionBox box2 = new CollisionBox(2, 2, 1, 3);
CollisionBox box3 = new CollisionBox(0, 0, 5, 2);
box1.collidesWith(box2);                // should return true.
box1.collidesWith(box3);                // should return true.
box2.collidesWith(box3);                // should return false.
box1.isSmallerOverlapVertical(box2);    // should return false.
box1.isSmallerOverlapVertical(box3);    // should return true.
box2.moveTo(3, 2);
box1.isHigherThan(box2);                // should return true.
box1.verticalDifference(box2);          // should return 2.
box2.verticalDifference(box1);          // should return 2.
box2.isLeftOf(box1);                    // should return false.
box1.horizontalDifference(box2);        // should return 1.
box2.horizontalDifference(box1);        // should return 1.

Submission: Please submit CollisionBox.java to the grading system.

POTD 16 - Library.java - Due: Friday, March 27, 11:00 AM

We are now going to write a class to represent a Library. You will use the LibraryBook class you implemented in POTD14. Please implement the following API in your class:

Library
− name : String
− books : ArrayList<LibraryBook>
− members : ArrayList<String>
+ Library(name: String, books: ArrayList<LibraryBook>, members: ArrayList<String>)
+ setName(name: String) : void
+ getName() : String
+ setBooks(books: ArrayList<LibraryBook>) : void
+ getBooks() : ArrayList<LibraryBook>
+ setMembers(members: ArrayList<String>) : void
+ getMembers() : ArrayList<String>
+ addBook(book: LibraryBook) : boolean
+ addMember(memberName: String) : boolean
+ hasBook(book: LibraryBook) : boolean
+ getAllBooksByAuthor(author: String) : ArrayList<LibraryBook>
+ getAllAvailableBooksByAuthor(author: String) : ArrayList<LibraryBook>
+ checkOutBook(member: String, book: LibraryBook) : boolean
+ advanceDay() : int
+ toString() : String
Constructor

The constructor should save the the name of the library, the books list, and the members list.

addBook(LibraryBook book) and addMember(String memberName)

The addBook(LibraryBook book) and addMember(String memberName) should attempt to add the parameter to the appropriate list without adding duplicates. If the parameter is already in the list and thus cannot be added again, the method should return false. If the parameter is successfully added to the list, the method should return true.

hasBook(LibraryBook book)

The hasBook(LibraryBook book) method should return true if the library has the given book in its ArrayList of LibraryBooks.

getAllBooksByAuthor(String author)

The getAllBooksByAuthor(String author) method should return an ArrayList of books written by the given author.

getAllAvailableBooksByAuthor(String author)

The getAllAvailableBooksByAuthor(String author) method should return an ArrayList of books written by the given author that are not currently checked out.

checkOutBook(String member, LibraryBook book)

The checkOutBook(String member, LibraryBook book) method should attempt to call LibraryBook’s checkOut method on the given book if and only if the library has that member and that book in the appropriate ArrayLists. The method returns true if you are able to successfully call LibraryBook’s checkOut method, otherwise the method should return false.

advanceDay()

The advanceDay() method should advance the day for every book in the library and count how many books have been returned on a given day. Here, you should rely on LibraryBook’s advanceDay() method to “do the work,” and should not be manipulating any LibraryBook’s fields.

toString()

The toString() method will return a string of the format “Name - # books and # members”. See the examples below. The quotation marks in the examples just denote the beginning and end of the string - the string you return should not contain quotation marks.

Constraints

DO NOT use a Scanner for any part of this assignment.

Using our LibraryBook implementation

If your LibraryBook.java passed all our tests cases, you should be good to go. But if not, you can use a reference implementation istead by doing the following:

  1. Make a new Java Project in Eclipse that does not have LibraryBook.java inside it.
  2. Download LibraryBook.jar to your hard drive somewhere.
  3. From your operating system’s file browser, drag the LibraryBook.jar you just downloaded into your new Eclipse project (the project folder itself, not the src folder inside it). If it asks, pick “Copy files here” (if not, don’t worry about it).
  4. In the Package Explorer in Eclipse, right-click on LibraryBook.jar and select Build Path → Add to Build Path
  5. If you already started Library.java in another project, drag it into the new project’s src folder

As long as you work on Library.java in this new project and do not add a LibraryBook.java to it, your code will use our reference implementation of LibraryBook instead of the one you wrote.

Example
Example Usage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
ArrayList<String> members = new ArrayList<String>(Arrays.asList("Steph", "Matt", "Luther", "Mark", "David"));
LibraryBook horton = new LibraryBook("Horton Hears a Hoo", "Dr. Seuss");
horton.checkOut("Steph");
for(int x = 0; x < 13; x++) {
  horton.advanceDay();       // returns false each time
}
LibraryBook places = new LibraryBook("Oh the Places You'll Go", "Dr. Seuss");
LibraryBook cat = new LibraryBook("The Cat in the Hat", "Ted Geisel");
ArrayList<LibraryBook> books = new ArrayList<LibraryBook>(Arrays.asList(horton, places, cat));

Library library = new Library("Clark", books, members);

library.toString();          // should return "Clark - 3 books and 5 members" 
new Library("Alderman", new ArrayList<LibraryBook>(), new ArrayList<String>()).toString();
                              // should return "Alderman - 0 books and 0 members"
library.addBook(horton)            // should return false
library.addBook(new LibraryBook("Green Eggs and Ham", "Dr. Seuss"))
                              // should return true
library.addMember("Jim")     // should return true
library.addMember("Steph")       // should return false
library.hasBook(horton)            // should return true
library.hasBook(new LibraryBook("The Lorax", "Dr. Seuss")
                              // should return false
library.getAllBooksByAuthor("Dr. Seuss")
                              // should return an ArrayList<LibraryBook> containing {Horton Hears a Hoo, Oh the Places You'll Go, Green Eggs and Ham}
library.getAllAvailableBooksByAuthor("Dr. Seuss")
                              // should return an ArrayList<LibraryBook> containing {Oh the Places You'll Go, Green Eggs and Ham}
library.checkOutBook("Matt", horton)
                              // should return false
library.checkOutBook("Luther", places)
                              // should return true
library.advanceDay()         // should return 1 (for Horton Hears a Hoo)<br>

Submission: Please submit Library.java to the grading system. There is no need to submit LibraryBook.java for this assignment.

POTD 15 - Person.java - Due: Wednesday, March 25, 11:00 AM

We are now going to write a class to represent a Person. You will implement the following API in your class:

Person
− givenName : String
− familyName : String
− givenComesFirst : boolean
+ Person(givenName: String, familyName: String, boolean givenComesFirst)
+ Person(givenName: String, familyName: String)
+ setGivenName(givenName: String) : void
+ getGivenName() : String
+ setFamilyName(familyName: String) : void
+ getFamilyName() : String
+ isGivenFirst() : boolean
+ sameFamilyAs(person: Person) : boolean
+ childWithGivenName(givenName: String) : Person
+ toString() : String
Constructors

The first constructor should set givenName, familyName, and givenComesFirst based on the provided arguments.

The second constructor should set givenName and familyName based on the provided arguments. It should set givenComesFirst to true, as a default value.

sameFamilyAs(Person person)

The sameFamilyAs method returns true if this person has the same familyName as the provided argument. The value of givenComesFirst for either person is not considered.

childWithGivenName(String givenName)

This childWithGivenName method creates a new person with the same familyName and givenComesFirst values as the current person, with the givenName field set to the provided argument. Return the person object that was created.

toString()

The toString() method will return a string based on the value of givenComesFirst. See the examples below. The quotation marks in the examples denote the beginning and end of the string - the string you return should not contain quotation marks.

  • If givenComesFirst is true, the string should be “givenName familyName”.
  • If givenComesFirst is false, the string should be “familyName givenName”. See the examples below.
Constraints

DO NOT use a Scanner for any part of this assignment.

Example
Example Usage
1
2
3
4
5
6
7
8
Person p1 = new Person("Mark", "Sherriff");
Person p2 = new Person("Luther", "Tychonievich", true);
Person p3 = new Person("Janos Lajos", "Neumann", false);
Person p4 = p1.childWithGivenName("Sammy");
p1.sameFamilyAs(p4);       // returns true
p1.sameFamilyAs(p2);       // returns false
p3.toString();               // returns "Neumann Janos Lajos"
p4.toString();               // returns "Sammy Sherriff"

Submission: Please submit Person.java to the grading system.

POTD 14 - LibraryBook.java - Due: Monday, March 23, 11:00 AM

We are now going to write a class to represent a LibraryBook. You will implement the following API in your class:

LibraryBook
− title : String
− author : String
− checkedOut : boolean
− daysUntilDue : int
− whoCheckedOut : String
+ LibraryBook(title: String, author: String)
+ setTitle(title: String) : void
+ getTitle() : String
+ setAuthor(author: String) : void
+ getAuthor() : String
+ isCheckedOut() : boolean
+ getDaysUntilDue() : int
+ getWhoCheckedOut() : String
+ checkOut(whoCheckedOut: String) : boolean
+ advanceDay() : boolean
+ toString() : String
Constructor

The constructor should set title and author based on the provided arguments, set checkedOut to false, set daysUntilDue to 0, and set whoCheckedOut to the empty string.

checkOut(String whoCheckedOut)

The checkOut(String whoCheckedOut) method should first check to see if the book is already checked out by looking at the value of checkedOut.

  • If the book is already checked out, return false to indicate the book could not successfully be checked out.
  • If the book is not already checked out, set checkedOut to true, set daysUntilDue to 14 (two weeks), set whoCheckedOut to the given parameter, and return true to indicate the book was successfully checked out.
advanceDay()

The advanceDay() method should first check to see if the book is already checked out by looking at the value of checkedOut.

  • If the book is checked out, the advanceDay() method should subtract one from daysUntilDue.
    • If daysUntilDue is now 0, set checkedOut to false and whoCheckedOut to the empty string, and return true.
    • If daysUntilDue is greater than 0, return false.
  • If the book is not checked out, return false.
toString()

If the book is not checked out, the toString() method will return a string in the format “Title - Author”. If the book is checked out, the toString() method will return a string in the format “Title - Author\nChecked out by Person for # more day(s).” The quotation marks here just denote the beginning and end of the string - the string you return should not contain quotation marks. See the examples below.

Constraints

DO NOT use a Scanner for any part of this assignment.

Example
Example Usage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
LibraryBook book = new LibraryBook("Horton Hears a Hoo", "Dr. Seuss");
book.isCheckedOut();     // returns false
book.getDaysUntilDue();      // returns 0
book.getWhoCheckedOut(); // returns ""
book.checkOut("Matt");       // returns true
book.isCheckedOut();     // returns true
book.checkOut("Steph");      // returns false
book.advanceDay();           // returns false
for(int x = 0; x < 12; x++) {
  book.advanceDay();     // returns false each time (12 total)
}
book.toString();         // returns "Horton Hears a Hoo - Dr. Seuss\nChecked out by Matt for 1 more day(s)."
book.advanceDay();           // returns true
book.toString();         // returns "Horton Hears a Hoo - Dr. Seuss"

Submission: Please submit LibraryBook.java to the grading system.

POTD 13 - LousListNumbers.java - Due: Friday, March 5, 11:00 AM

For this lab you’ll write a single class containing two static methods. If you want to add more methods to the class (such as a main method for testing) you may; all we will look at are the two methods we ask you to write.

These methods will all interface with the Lou’s List csv; recall from POTD 12 that a URL like

http://stardock.cs.virginia.edu/louslist/Courses/view/CS

will return many lines like

1
CS;1110;001;Introduction to Programming;Mark Sherriff;Lecture;3;true;false;true;false;true;1100;1150;Rice Hall 130;148;147;38.031639;-78.510811

and that the fields are (in order):

  • Dept ID (0)
  • Course Number (1)
  • Section (2)
  • Course Title (3)
  • Instructor (4)
  • Type of class (5)
  • Hours (6)
  • Monday (7)
  • Tuesday (8)
  • Wednesday (9)
  • Thursday (10)
  • Friday (11)
  • Start Time (12)
  • End Time (13)
  • Location (14)
  • Enrollment (15)
  • Allowable Enrollment (16)
  • Latitude (17)
  • Longitude (18)

One method will need to access the start and end times. Start and end times are expressed in the CSV as a 3- or 4-character string representing a 24-hour clock so, e.g., CS 1110 section 102 starts at 930 and ends at 1045, for a duration of 75 minutes and CS 2150 section 105 starts at 1930 and ends at 2105 for a duration of 95 minutes.

Some sections have a listed start and end time of -1, meaning they do not have a fixed schedule.

public static double meanDurationInMinutes(String department) throws Exception

Returns that average duration of all sections (of ANY type) for the given department. You’ll need to compute the durations based on the start and end times. Ignore sections with no start or end time (i.e., -1 in the csv).

When you submit it, meanDurationInMinutes must not use either System.in or System.out. You are welcome to use System.out.println calls during coding to help you debug, but remove them all before submission.

Example: If you invoke meanDurationInMinutes("DRAM") you should get back a number 96.14285714285714. You could test this example by adding a line like

1
System.out.println(LousListNumbers.meanDurationInMinutes("DRAM"));

to a main method in any file you want.

Example: If you invoke meanDurationInMinutes("CS") you should get back a number 73.73417721518987. You could test this example by adding a line like

1
System.out.println(LousListNumbers.meanDurationInMinutes("CS"));

to a main method in any file you want.

public static void classLocations(String department, double lat, double lon, int digits) throws Exception

Prints all class sections (lecture and lab ONLY) for the given department that are taught at the given latitude and longitude. Provided latitude (lat) and longitude (lon) locations, as well as latitude and longitude locations read from the website, should be rounded to the given digits after the decimal place before comparison. digits will always be greater than 0.

Does not return anything (must be void) and must not use System.in (but should use System.out).

Example: If you invoke classLocations("DRAM", 38.03, -78.50, 2) it should print

1
2
 DRAM 2810 section 100
 DRAM 2810 section 101

You could test this example by adding a line like

1
LousListNumbers.classLocations("DRAM", 38.03, -78.50, 2)

to a main method in any file you want.

Example: If you invoke classLocations("CS", 38.03312345, -78.51012345, 3) it should print

1
2
3
4
5
6
7
8
 CS 3205 section 001
 CS 3330 section 001
 CS 4102 section 002
 CS 4501 section 006
 CS 4501 section 007
 CS 4610 section 001
 CS 5501 section 002
 CS 6501 section 002

You could test this example by adding a line like

1
LousListNumbers.classLocations("CS", 38.03312345, -78.51012345, 3);

to a main method in any file you want.

Submission: Please submit one .java file named LousListNumbers.java to the grading system.

POTD 12 - LousListMethods.java - Due: Wednesday, March 4, 11:00 AM

For this lab you’ll write a single class containing two static methods. If you want to add more methods to the class (such as a main method for testing) you may; all we will look at are the two methods we ask you to write.

These methods will all interface with the Lou’s List csv; recall from POTD 9 that a URL like

http://stardock.cs.virginia.edu/louslist/Courses/view/CS

will return many lines like

1
CS;1110;001;Introduction to Programming;Mark Sherriff;Lecture;3;true;false;true;false;true;1100;1150;Rice Hall 130;148;147;38.031639;-78.510811

and that the fields are (in order):

  • Dept ID (0)
  • Course Number (1)
  • Section (2)
  • Course Title (3)
  • Instructor (4)
  • Type of class (5)
  • Hours (6)
  • Monday (7)
  • Tuesday (8)
  • Wednesday (9)
  • Thursday (10)
  • Friday (11)
  • Start Time (12)
  • End Time (13)
  • Location (14)
  • Enrollment (15)
  • Allowable Enrollment (16)
  • Latitude (17)
  • Longitude (18)

Several methods will need to access the start and end times. Start and end times are expressed in the CSV as a 3- or 4-character string representing a 24-hour clock so, e.g., CS 1110 section 102 starts at 1100 and ends at 1215, for a duration of 75 minutes and CS 2150 section 105 starts at 1330 and ends at 1515 for a duration of 105 minutes.

Some sections have a listed start and end time of -1, meaning they do not have a fixed schedule.

public static ArrayList<String> instructors(String department) throws Exception

Returns a list containing each instructor listed in Lou’s List for the given deparment. Do not count the same instructor twice: for example, Mark Sherriff is listed as instructor for 19 courses but should only appear in the resulting list once.

When you submit it, instructors must not use either System.in or System.out. You are welcome to use System.out.println calls during coding to help you debug, but remove them all before submission.

Example: If you invoke instructors("EAST") you should get back a list with four elements: “Benedetta Lomi”, “Staff”, “Michiko Wilson”, and “Dorothy Wong”. The order in which they come back does not matter. You could test this example by adding a line like

1
System.out.println(LousListMethods.instructors("EAST"));

to a main method in any file you want.

Example: If you invoke instructors("URDU") you should get back a list with one element: Griffith Chaussee". You could test this example by adding a line like

1
System.out.println(LousListMethods.instructors("URDU"));

to a main method in any file you want.

public static void courseConflicts(String department, int hour, int minute) throws Exception

Prints out all of the sections in the department that overlap with the specified time of day, in the order they appear on the page. Consider a time as overlapping with its starting time but not its own ending time, so CS 1110 section 001 (1100 to 1150) conflicts with 11:00 and 11:49 but not with 10:59 or 11:50. Ignore sections with no start or end time (i.e., -1 in the csv).

Does not return anything (must be void) and must not use System.in (but should use System.out).

Example: If you invoke courseConflicts("ENGR", 9, 50) it should print

1
 ENGR 1559 section 001 

You could test this example by adding a line like

1
LousListMethods.courseConflicts("ENGR", 9, 50);

to a main method in any file you want.

Example: If you invoke courseConflicts("CS", 12, 50) it should print

1
2
3
4
5
6
 CS 1110 section 103
 CS 1110 section 110
 CS 2102 section 001
 CS 3102 section 001
 CS 4414 section 001
 CS 6501 section 003

You could test this example by adding a line like

1
LousListMethods.courseConflicts("CS", 12, 50);

to a main method in any file you want.

Submission: Please submit one .java file named LousListMethods.java to the grading system.

POTD 11 - Hangman.java - Due: Monday, March 2, 11:00 AM

Write a program that will let the user play Hangman.

Setup

Your program should prompt the user to enter a word. If the user enters a word, that will be the word the player guesses.

If the user does not enter a word (i.e. they enter the empty string) you should prompt them for a URL. This URL will point to a page containing one line, a comma-separated list of words. You should use Random to select a word from the list.

Hint: Determine how many words are in the list, use this to select a random number in the appropriate range and index the list with the random number.

You may test with the following URL: https://cs1110.cs.virginia.edu/hangmanwords.txt

Suggested Approach
  1. Create a display string with the right number of hyphens (loop and add one for each letter in the target word).
  2. For each letter they guess,
    1. If the letter is not in the target word, count a miss (the String class’s indexOf method can help with that)
    2. Otherwise, make a new display string by
      1. loop through the target word’s letters
        1. if the letter matches their guess, add it to the new display string
        2. if the letter does not match their guess, copy whatever was in that spot of the old display string over
      2. replace the old display string with the new one
    3. If they have too many misses, tell them they lose; if there are no - left in the display string, tell them they win.
Gameplay

The user will guess letters until either:

  • They have correctly guessed all the letters in the word.
  • They have incorrectly guessed 6 times.

At each turn, display the player’s progress by showing the word they’re guessing in all capital letters, with all non-guessed characters replaced by dashes (“-”).

The specific output format is shown in the examples below:

Enter a word: HANGMAN
[-------] You have 6 left, enter a letter: A
Correct!
[-A---A-] You have 6 left, enter a letter: B
Incorrect!
[-A---A-] You have 5 left, enter a letter: C
Incorrect!
[-A---A-] You have 4 left, enter a letter: D
Incorrect!
[-A---A-] You have 3 left, enter a letter: E
Incorrect!
[-A---A-] You have 2 left, enter a letter: F
Incorrect!
[-A---A-] You have 1 left, enter a letter: G
Correct!
[-A-G-A-] You have 1 left, enter a letter: K
You lose! The word was “HANGMAN”

Enter a word: COMPUTER
[--------] You have 6 left, enter a letter: E
Correct!
[------E-] You have 6 left, enter a letter: B
Incorrect!
[------E-] You have 5 left, enter a letter: C
Correct!
[C-----E-] You have 5 left, enter a letter: A
Incorrect!
[C-----E-] You have 4 left, enter a letter: P
Correct!
[C--P--E-] You have 4 left, enter a letter: E
Correct!
[C--P--E-] You have 4 left, enter a letter: R
Correct!
[C--P--ER] You have 4 left, enter a letter: M
Correct!
[C-MP--ER] You have 4 left, enter a letter: A
Incorrect!
[C-MP--ER] You have 3 left, enter a letter: T
Correct!
[C-MP-TER] You have 3 left, enter a letter: O
Correct!
[COMP-TER] You have 3 left, enter a letter: U
You win! The word was “COMPUTER”

Enter a word: Aa
[--] You have 6 left, enter a letter: a
You win! The word was “AA”

For the below example, the random word selected was “POTATO”. This will vary on each run based on which word is randomly selected.

Enter a word:
Enter a URL: http://cs1110.cs.virginia.edu/hangmanwords.txt
Selecting a random word.
[------] You have 6 left, enter a letter: E
Incorrect!
[------] You have 5 left, enter a letter: O
Correct!
[-O---O] You have 5 left, enter a letter: C
Incorrect!
[-O---O] You have 4 left, enter a letter: T
Correct!
[-OT-TO] You have 4 left, enter a letter: S
Incorrect!
[-OT-TO] You have 3 left, enter a letter: P
Correct!
[POT-TO] You have 3 left, enter a letter: A
You win! The word was “POTATO”

Notes
  • We will only grade you on words and guesses made up of letters in the alphabet.
  • Convert both the word and the guesses to upper case; word Aa and guess a should say You win! The word was "AA".
  • If the user guesses a letter twice, handle it the same as the first time. If it initially matched a letter in the string, it should still count as a match and not as a miss. If it was initially a miss, it will count as another miss. This is shown in the examples above.
  • You may assume that the user only types single-letter guesses.
Submission

Please submit one .java file named Hangman.java to the grading system.

POTD 10 - LousListProfessor.java - Due: Monday, February 23, 11:00 AM

Write a program that will read from a minimal version of Lou’s List to determine the instructor who teaches the most lecture sessions in a specified department.

The data is accessible in the same way as POTD 9, and is formatted identically. The root URL of our site is:

http://stardock.cs.virginia.edu/louslist/Courses/view/

Your program should prompt the user for a department mnemonic. It should then query the website, read the data, and use it to determine which instructor teaches the most sections in that department and how many sections they teach.

Here are some extra requirements:

  • We will only consider Lecture sections.
  • Ignore courses taught by “Staff”.
  • In the case of a tie, print the instructor whose name appears first alphabetically (by first name).
  • Your code must run in under 1 second. That means you can’t read the same URL more than once per run. If you have trouble solving the problem in a single pass through the input, download CachingURL.java to your Eclipse project and use CachingURL instead of URL in your code. It will store the contents of the page accessed on your hard drive the first time you access it, making subsequent accesses much faster.

For this assignment, you should make use of ArrayLists as you are handling data from Lou’s list. See the complete API for in-depth info. Here are some tips you will find useful:

Using ArrayList
1
2
3
4
ArrayList<String> myList = new ArrayList<String>();     // Create a new ArrayList that holds Strings.
myList.add("hello");     // Add the string "hello" to my list.
boolean b1 = myList.contains("hello");     // b1 will be true.
boolean b2 = myList.contains("goodbye");       // b2 will be false.

An example run might be:

Enter a department: CS
Mark Floryan teaches the most lecture sections (4) in the CS department.

Another run might be:

Enter a department: BIOL
Mark Kopeny teaches the most lecture sections (4) in the BIOL department.

Another run might be: Enter a department: PSYC
Angeline Lillard teaches the most lecture sections (2) in the PSYC department.

You can assume we will only ask for valid department mnemonics.

Your program must be able to run any input in under 1 second. If you try to read a URL several times you will probably not reach that limit. If you have trouble solving the problem in a single pass through the input, download CachingURL.java to your Eclipse project and use CachingURL instead of URL in your code. It will store the contents of the page accessed on your hard drive the first time you access it, making subsequent accesses much faster.

Submission: Please submit one .java file named LousListProfessor.java to the grading system.

POTD 9 - LousListElective.java - Due: 20 Feb 2015, 11:00 AM

Write a program that will read from a minimal version of Lou’s List to determine the name and instructor of the most popular 4000+ level class section in a specified department.

We have gathered the data from Lou’s List and put it online in a more machine-readable format. The root URL of our site is:

http://stardock.cs.virginia.edu/louslist/Courses/view/

By adding various department mnemonics to the end of the URL, you can view the info for that particular department. For instance:

http://stardock.cs.virginia.edu/louslist/Courses/view/CS

will list all the CS courses for this semester.

A single section of a course is represented like this:

CS;1110;001;Introduction to Programming;Mark Sherriff;Lecture;3;true;false;true;false;true;1100;1150;Rice Hall 130;148;147;38.031639;-78.510811

The fields are (in order):

  • Dept ID (0)
  • Course Number (1)
  • Section (2)
  • Course Title (3)
  • Instructor (4)
  • Type of class (5)
  • Hours (6)
  • Monday (7)
  • Tuesday (8)
  • Wednesday (9)
  • Thursday (10)
  • Friday (11)
  • Start Time (12)
  • End Time (13)
  • Location (14)
  • Enrollment (15)
  • Allowable Enrollment (16)
  • Latitude (17)
  • Longitude (18)

Your program should prompt the user for a department mnemonic. It should then query the website, read the data, and use it to determine which 4000+ level class section has the most students enrolled.

Here are some extra requirements:

  • We will only consider Lecture sections.
  • In the case of a tie, print the course with the higher course number.
  • Your code must run in under 1 second. That means you can’t read the same URL more than once per run. If you have trouble solving the problem in a single pass through the input, download CachingURL.java to your Eclipse project and use CachingURL instead of URL in your code. It will store the contents of the page accessed on your hard drive the first time you access it, making subsequent accesses much faster.

An example run might be:

Enter a department: CS
The most popular 4000+ level course in the CS department is CS 4710-001 (Artificial Intelligence) with 135 students, and is taught by Mark Floryan.

Another run might be:

Enter a department: BIOL
The most popular 4000+ level course in the BIOL department is BIOL 4260-001 (Cellular Mechanisms) with 48 students, and is taught by W Wormington.

Another run might be: Enter a department: PSYC
The most popular 4000+ level course in the PSYC department is PSYC 5310-001 (Developmental Psycholinguistics) with 20 students, and is taught by John Bonvillian.

You can assume we will only ask for valid department mnemonics.

Submission: Please submit one .java file named LousListElective.java to the grading system.

POTD 8 - Nim.java - Due: Wednesday, February 18, 11:00 AM

Write a program that will play the game of Nim.

The Game of Nim is a well-known game with a number of variants. One particularly interesting version plays like this:

Assume you have a large pile of marbles. Two players alternate taking marbles from the pile. In each move, a player is allowed to take between 1 and half of the total marbles. So, for instance, if there are 64 marbles in the pile, any number between and including 1 and 32 is a legal move. Whichever player takes the last marble loses.

Write a program called Nim.java in which a human player plays against the computer. The program should first ask for how many marbles are in the starting pile. Then the program should ask for a character for who will start the game (‘p’ for player, ‘c’ for computer). The game will then alternate between the computer and the player, asking the player for how many marbles they want to take (making sure they take a positive integer between 1 and half the pile and making them pick another number if they do it wrong).

The computer should always take enough marbles to make the size of the pile a power of 2 minus 1 - such as 3, 7, 15, 31, 63, etc. If that’s not possible, the computer will take one marble.

You should find that the computer, if it gets to go first, will always win. Similarly, if you go first and know the strategy, you’ll always win!

An example run might be:

The Game of Nim

Number of marbles are in the pile: 100
Who will start? (p or c): c
The pile has 100 marbles in it.
The computer takes 37 marble(s).
The pile has 63 marbles in it.
How many marbles do you want to take? (1-31): 4
The pile has 59 marbles in it.
The computer takes 28 marble(s).
The pile has 31 marbles in it.
How many marbles do you want to take? (1-15): 13
The pile has 18 marbles in it.
The computer takes 3 marble(s).
The pile has 15 marbles in it.
How many marbles do you want to take? (1-7): 6
The pile has 9 marbles in it.
The computer takes 2 marble(s).
The pile has 7 marbles in it.
How many marbles do you want to take? (1-3): 2
The pile has 5 marbles in it.
The computer takes 2 marble(s).
The pile has 3 marbles in it.
How many marbles do you want to take? (1-1): 1
The pile has 2 marbles in it.
The computer takes 1 marble(s).
The pile has 1 marbles in it.
How many marbles do you want to take? (1-1): 1
The computer wins!

Another run might be:

The Game of Nim

Number of marbles are in the pile: 64
Who will start? (p or c): p
The pile has 64 marbles in it.
How many marbles do you want to take? (1-32): 1
The pile has 63 marbles in it.
The computer takes 1 marble(s).
The pile has 62 marbles in it.
How many marbles do you want to take? (1-31): 45
How many marbles do you want to take? (1-31): 90
How many marbles do you want to take? (1-31): 31
The pile has 31 marbles in it.
The computer takes 1 marble(s).
The pile has 30 marbles in it.
How many marbles do you want to take? (1-15): 15
The pile has 15 marbles in it.
The computer takes 1 marble(s).
The pile has 14 marbles in it.
How many marbles do you want to take? (1-7): 7
The pile has 7 marbles in it.
The computer takes 1 marble(s).
The pile has 6 marbles in it.
How many marbles do you want to take? (1-3): 3
The pile has 3 marbles in it.
The computer takes 1 marble(s).
The pile has 2 marbles in it.
How many marbles do you want to take? (1-1): 1
The pile has 1 marbles in it.
The computer takes 1 marble(s).
The player wins!

Submission: Please submit one .java file named Nim.java to the grading system.

POTD 7 - CreditCard.java - Due: Monday, February 16, 11:00 AM

Write a program to compute if a given number is a valid credit card number.

Credit card numbers have what is called a check digit. This is a simple way of detecting common mis-typings of card numbers. You’ll want to read the credit-card number as a String so you can access each digit easily (using charAt()). The algorithm is as follows:

  1. Form a sum of every other digit, including the right-most digit; so 5490123456789128 sums to 8+1+8+6+4+2+0+4 = 33
  2. Form double each remaining digit, then sum all the digits that creates it; the remaining digits in our example (5 9 1 3 5 7 9 2) double to 10 18 2 6 10 14 18 4, which sums to 1+0+1+8+2+6+1+0+1+4+1+8+4 = 37
  3. Add the two sums above (33+37 = 70)
  4. If the result is a multiple of 10 (i.e., its last digit is 0) then it was a valid credit card number.

An example run might be:

Type a credit card number (just digits): 1
1 is not a valid credit card number

Another run might be:

Type a credit card number (just digits): 240
240 is a valid credit card number

Another run might be:

Type a credit card number (just digits): 9548
9548 is a valid credit card number

Another run might be:

Type a credit card number (just digits): 5490123456789129
5490123456789129 is not a valid credit card number

Submission: Please submit one .java file named CreditCard.java to the grading system.

POTD 6 - Roman.java - Due: Friday, February 13, 11:00 AM

Write a program to compute the roman numeral representation of integers.

Given an integer larger than 0 and less than 4000, convert it to roman numerals. You can find the rules for this here, or simply search for it online.

There are many ways to do this, some more efficient than others. If it works and you wrote it yourself that’s good enough.

If the integer they provide is not in the right range, print “Input must be between 1 and 3999”

An example run of the program might look like:

Enter an integer: 1997
In roman numerals, 1997 is MCMXCVII

Another run might look like:

Enter an integer: 5820
Input must be between 1 and 3999

Submission: Please submit one .java file named Roman.java to the grading system.

POTD 5 - Caesar.java - Due: Wednesday, February 11, 11:00 AM

Write a program to decode text that was encoding using the Caesar cipher.

Caesar’s cihper works by shifting every letter in a piece of text three characters over, so “A” becomes “D”, “B” becomes “E”, etc. In Java, this is simple because we can simply add and subtract numbers from chars. Such math moves along the ascii table, which happens to line up with the alphabet nicely.

Write a method to decode a Caesar-cipher encoded text of exactly twelve characters in length. Don’t worry about wrapping around the end of the alphabet; Caesar may have encoded “Z” as “C”, but we’ll encode it as “]” instead, per the ascii table.

An example run of the program might look like:

Enter your cipher text: vr#kdsslqhvv
The decoded phrase is: so happiness

An example run of the program might look like:

Enter your cipher text: Idvflqdwlqj$
The decoded phrase is: Fascinating!

Submission: Please submit one .java file named Caesar.java to the grading system. (note the spelling: ae not e or ea; and ar not er)

POTD 4 - HigherLower.java - Due: Monday, February 9, 11:00 AM

Write a program to play a simple guessing game with you.

The computer will pick a number between 1 and 100, then give you 5 guesses. If you guess right, it will say “You win!”. If you guess higher or lower than correct, it will say “The number is higher than that.” (or lower). If after five guesses they still don’t know the number, print “You lose; the number was x.” where x was the number you were to guess.

Before the game begins, ask what number to pick. If they say “−1”, pick randomly; otherwise, use their number even if it is outside the 1–100 range. You can get a random integer between 0 and n with the code (int)(Math.random()*(n+1)) or by creating a Random object as you did in lab.

An example run of the program might look like:

What should the answer be? 19
Guess a number: 9
The number is higher than that.
Guess a number: 40
The number is lower than that.
Guess a number: 19
You win!

Another run might look like:

What should the answer be? -1
Guess a number: 5
The number is higher than that.
Guess a number: 100
The number is lower than that.
Guess a number: 50
The number is lower than that.
Guess a number: 25
The number is lower than that.
Guess a number: 12
You lose; the number was 7.

Submission: Please submit one .java file named HigherLower.java to the grading system.

POTD 3 - BMR.java - Due: Friday, February 6, 11:00 AM

Write a program to compute your Basal Metabolic Rate (how many calories you burn while resting).

We’ll use the Mifflin St Jeor equation, for which we need to know four things: your mass in kilograms m, your height in centimeters h, your age in years a, and your gender. Gender is used to select a constant s: it’s +5 for males, −161 for females. We then comine it all using the following formula:

BMR Equation

An example run might be:

What is your mass (kg)? 59
What is your height (cm)? 168
What is your age (years)? 55
Are you female (yes/no)? yes
Your BMR is 1204.0 Calories per day

Another run might be:

What is your mass (kg)? 100
What is your height (cm)? 187
What is your age (years)? 20
Are you female (yes/no)? no
Your BMR is 2073.75 Calories per day

Submission: Please submit one .java file named BMR.java to the grading system.

POTD 2 - Dating.java - Due: Wednesday, February 4, 11:00 AM

Write a program that uses a folk rule to tell you the age range of people you can date.

There is a folk rule that says you can date people as young as half your age plus seven years old. This suggests they can date you if they are as old as twice your age minus thirteen.

An example run of the program might look like:

How old are you? 17
You can date people between 15 and 21 years old

Another run might look like:

How old are you? 70
You can date people between 42 and 127 years old

Please match our prompts, etc, exactly. Your program should work for any integer age ≥ 14 that we provide.

Submission: Please submit one .java file named Dating.java to the grading system.

POTD 1 - C2F.java - Due: Monday, February 2, 11:00 AM

Write a program to convert from Celsius to Fahrenheit.

You should prompt the user for the current temperature in Celsius, then print out the corresponding temperature in Fahrenheit (recall that 5(F − 32) = 9 C). An example run of the program might look like:

What is the temperature in Celsius? 31
It is 87.8 degrees Fahrenheit

Another run might look like:

What is the temperature in Celsius? 100
It is 212.0 degrees Fahrenheit

One quick hint: Consider that int is used for integers, while double is used for decimal numbers.

Please match our prompts, etc, exactly. Your program should work for any integer Celsius temperature we provide.

Submission: Please submit one .java file named C2F.java to the grading system.

Current POTD

Upcoming POTDs

Team Projects