RU beehive logo ITEC dept promo banner
ITEC 120
2007fall
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

hw12
lists and loops
Explorers with many Treasures

  1. (3pts) Rewrite the statement
      return (e.getSong().getLastPlayed().comesBefore( s.getLastPlayed()));
    
    so that it uses local variables to give names to (at least two of) the subresults. Your answer will be at least three lines of code, only the last of which is a return statement.
    (As you probably surmised: s is a Song, and getLastPlayed() returns a Date.)
  2. (1pt) The statement “return x = 5;” is…
    1. A well-written return statement
    2. A well-written assignment statement
    3. Extremely confused about whether it is returning a result or assigning to a variable.
  3. (3pts) What is the syntax of a for-each loop?
                     (                  :                  ) {
                       
      }
    
  4. (3pts) What is the syntax of a while loop?
                     (                  ) {
                       
      }
    
  5. (1pt) true or false?: even if a return statement is used inside a for-each loop, every element of the list is processed.
  6. The follow problems refer to the classes and methods in exam2-soln. In these examples, a list-of-MusicLibraryEntrys is informally referred to as a playlist.
  7. (2pts) Complete the following function:
    /** Count the number of Entries by given certain artist, in a playlist.
     * @param ents a playlist (“entries”).
     * @param artst The artist to look for.
     * @return the number of things in ents which refer to a song by artst.
     */
    static int howManyBy( java.util.LinkedList<MusicLibraryEntry> ents, String artst ) {
      int numSoFar = 0;
      for ( MusicLibraryEntry e : ents ) {
        if (e.getSong().get                ().equals(artst) ) {
          numSoFar =                 
          }
        }
      }
    
  8. (5pts) Complete the following function:
    /** Find the shortest song in a playlist.
     * @param ents The playlist (“entries”).  MUST BE NON-EMPTY.
     * @return a shortest song in ents.
     */
    static Song shortestSong( java.util.LinkedList<MusicLibraryEntry> ents, String artst ) {
                       shortestSoFar = ents.get(0).getSong();
      for ( MusicLibraryEntry e :                  ) {
        if (e.getSong().get                 <=                 .getLength())  {
                           = e.get                ();
          }
        }
      return shortestSoFar;
      }
    
    If there is more than one Song which tie for shortest, this implementation happens to return the one which occurs                  in ents.
  9. (5pts) Complete the following function. You may abbreviate “MusicLibraryEntry” as “MLE”, and “java.util.LinkedList<” as “List<” :
    /** Find all the copyrighted songs in a playlist.
     * @param ents The playlist (“entries”).
     * @return All the songs with copyrights within ents.
     */
    java.util.LinkedList<Song> allCRs( java.util.LinkedList<MusicLibraryEntry> ents ) {
      java.util.LinkedList<                > crsSoFar = new                                         ();
    
      for (                  e :                  ) {
        if (e.get                ().get                 )  {
          crsSoFar.add(                .get                () );
          }
        }
      return                 ;
      }
    
  10. (2pts) What lines does the following print out?
    (Hint: walk through the code by hand, keeping track of what each variable is.)
    int i = 2;
    int ssf = 0;
    while (i < 10) {
      ssf = ssf + i;
      System.out.println( "i=" + i + "; ssf = " + ssf );
      i = i+3;
      }
    

gRUe: Grand Rooms for Underground Explorers

Make a copy of your hw10 solution, as a new project hw12.

Part (b), 15pts, due Nov.12 (Mon) in class: Turn in the requested pictures and your documentation. No test cases required for turn-in, as this is I/O-based. (Do test each function before proceeding to the next, of course.) Don't turn in any of the code you wrote. When submitting to WebCT, it's fine to just attach your entire BlueJ folder.

Part (c), 25pts, due Nov.14 (Wed)Nov.16 (Fri) at the start of class: As usual, turn in your source code for Room, as well as the code for your updated Explorer method exploreOnce. You don't need to turn in the code for the Treasure method treasureListToString, as long as you do have roomListToString in class Room. Remember, we are now taking off for poor indentation!; if nothing else, paste into eclipse and use Ctrl-A Ctrl-I. When submitting to WebCT, it's fine to just attach your entire BlueJ folder.

  1. Write the method treasureListToString, which takes in a LinkedList<Treasure> and returns a String of the following form:
    (1) a small nugget -- Upon close inspection, the nugget glints of gold!
    (2) a fancy pen -- This pen can write in purple, green, and plaid.
    (3) chocolate egg -- The size of an ostrich egg, but made entirely of dark chocolate.
    
    Note that if there are three items in the list, there will be three newline characters in the result.
    (Should this method be static? What class should it live in?)
  2. A Room has a name and a description, and can hold zero or more Treasures. Two examples of rooms would be:
    name: Davis 225 lab
    description: This room is dark, the only light coming from an eerie screen saver.
    items: [a computer, a mouse]

    name: Mt. Everest, west ascent.
    description: The sun shines bright on the glacier above you.
    items: [a chocolate egg].
    1. create a class with these three attributes. What type should you use, to represent zero or more Treasures?
    2. write a constructor which takes two Strings for future semesters, only use the 2-arg constructor, Ian and a single Treasure as input. It creates a Room which initially contains that one Treasure.1
    3. Before proceeding, make several test cases: several Room objects. (You don't have to make exactly the examples above, but realize that before creating a Room object, you'll need to have a Treasure to place in it.)
    4. Write a public toString method for Rooms, which only returns the Room's name.
    5. For future semsters --Ian Write a Room method addItem(Treasure), which inserts a Treasure into the Room.
      Update your drop method(s) to use this method.
    6. Our game will want one special Room object, which all new Explorers will start in. Make a named constant STARTING_ROOM, and initialize it with some particular Room. (This is a static2 field.)
    7. (Optional, but will help you test your other methods, especially later:) Write a Room method boolean contains(Treasure t).
      Note that LinkedList has a method contains which you can use.
  3. Now that we have Rooms, we can have a place for explorers to hang out in!
    1. Go back to class Explorer, and add a field which holds (a reference to) the Explorer's current Room. Your constructor should intialize that field to the one designated constant Room.STARTING_ROOM. Update your javadoc comments method accordingly.

      To think about: Should this field be static? That is, if you have ten different Explorers, do they all have identically the same notion of their current Room? And if an Explorer later moves to a different Room, how will our program represent that? (To think about: What does the picture look like, before-and-after, for the objects involved? You'll need to draw a picture for #4, below.)

    2. Many things a player does will depend on which Room they are currently in. Write a getter function for the Explorer's Room.
    3. Write a setter function for the Explorer's Room. (Although this will be a function which won't be called by others, we'll use it for testing.)
    4. Write a Explorer method look(), which returns the detailed listing of the Explorer's current room. Make sure that if you set the explorer's room to be something different than their starting-room, then look() will suddenty describe their new location.
    5. Modify the dropLeft(), dropRight() methods so that the dropped Treasure is added to the Room's Treasures.
      Update your javadoc comments accordingly. (Leave grab() unchanged, for now.)
    At this point, you should be able to run a session similar to the following, in BlueJ's code pad3
    Explorer me = new Explorer( "Dora" );
    Treasure jc = new Treasure( "Jolt Cola", "An unopened 2liter bottle", 4.4 );4
    me.grab(jc)  // Note that jc was never actually in the room; we gave it directly to `me`.
    "You pick up a Jolt Cola."
    
    me.inventory()
    "You are carrying:
    left pocket: a Jolt Cola -- An unopened 2liter bottle
    right pocket: lint -- a little fluffy ball"
    me.look()
    "Davis 225 lab:
    This room is dark, the only light coming from an eerie screen saver.
    There is [a computer, a mouse].5."
    me.dropRightLeft()
    "You drop a Jolt Cola."
    me.look()
    "Davis 225 lab:
    This room is dark, the only light coming from an eerie screen saver.
    There is [a computer, a mouse, a Jolt Cola]."
    
    The above text is just a guideline, though you should include at least the same rough amount of information, and at least as human-readable.
  4. For part (b) (Monday): Draw a picture of the objects involved at the end of the above dialogue.
  5. Let's update grab so that it can (try to) take any of the items in the current Room, and when an item has been successfully grabbed then it is no longer in the Room's list of Treasures. More precisely: (It's difficult to re-use our previous version to get this augmented version. Don't worry much about trying to avoid repeated code. We'll see in an extra-credit homework, things will be much easier once we get rid of the left-pocket right-pocket distinction.)

    Once you have this working, the above Code Pad example should be similar, except that items won't disappear — dropping a bottle of cola leaves the room with both a computer and a cola. We might continue:

    me.dropLeft()
    "You have dropped a lint."
    me.dropLeft()
    "You have dropped a lint."
    me.look()
    "Davis 225 lab:
    This room is dark, the only light coming from an eerie screen saver.
    There is [a computer, a mouse, a Jolt Cola, a lint, a lint]."
    me.grab(1)
    "You have grabbed a mouse."6
    me.look();
    "Davis 225 lab:
    This room is dark, the only light coming from an eerie screen saver.
    There is [a computer, a Jolt Cola, a lint, a lint]."
    
    It doesn't matter where in the list new items are added, and don't worry too much about making your messages perfectly grammatical. (For instance, if there are no Treasures in the Room, then look() might return a message like "There is [].". Don't make the messages excessively long though — looking about the room should mention the name of items, but not their full description. (If you like, you can write a method Explorer.examine(int), which returns the full description of the with the given index.) You are certainly welcome to make your messages nicer, but that's not required for the grade, as long as the right Treasures are listed.

  6. Write roomListToString, which behaves analogously to treasureListToString. (That is, it takes in a LinkedList<Room>.)
    (You are allowed to mutter under your breath, about the practically-repeated code. Not until we mention interfaces and/or inheritance, in the last week of class, will we be able to rid ourselves of this repetition.)
  7. Write the following method, for TextIO:
      /** Have the user select an item from a list.
       * @param instruction A message describing what is being selected, e.g. "Choose your favorite treasure:"
       * @param items The list of Treasures to have the user choose from.  The list will not be modified.
       * @return an index into items, or the sentinel value -1, for no-choice-made.
       *    (The -1 might indicate that the user entered an invalid choice, or 
       *    maybe the changed their mind and cancelled the selecting.)
       *    The input is taken from the scanner.
       */
      int select( String instruction, LinkedList<Treasure> items ) 
    
    Hint: call both promptForInt and treasureListToString. Return -1 to represent “nothing selected after all”. Do not return anything other than a valid index, or -1. Anybody calling this method will need to specially check for a return value of -1.
  8. Update the Explorer method exploreOnce so that it knows about look.
  9. Update the Explorer method exploreOnce with command for grabbing things: it will prompt the user to choose one of the treasures in the explorer's current room, and (if the user doesn't cancel their choice) (try) to grab the item as indicated by the user.
  10. Write another version of select which takes a LinkedList<Room>. (We'll use this method next week.)
  11. (This problem can be done next week, although now is the logical place to put it:)
    Write a method explore which calls exploreOnce over and over until the user enters the command "quit".
    Do not add any extra fields. Hint: Instead, modify exploreOnce so that it returns a boolean.

1 So we can tell that in the example Rooms listed, the one containing two Treasures has had a Treasure added to it, since it was constructed.      

2Be sure to make this field static. If it is a regular field, then you are saying that every Room contains a Room inside of it; but of course that Room would then (by your definition) also contain a Room, which would contain …. If you mistakenly do this, BlueJ will make about 1000 recursive calls before spewing out a bunch of red lines saying “stack overflow”.      

3Remember that in the Code Pad, you don't want to include a semicolon when making a method call whose result you want to see, like grab and look. But, you must include a semicolon for assignment statements, since they return no result.      

4Okay, you can provide the fourth argument of "" to the Treasure constructor if you like. But don't you find it a bit annoying, that in order to indicate “use the default image-URL”, we have to pass in the empty string? We can do better, now that we know about overloading: you can write a second Treasure constructor which only takes three inputs, and uses that default image-URL. And since we're not getting rid of the old four-argument version, it doesn't break any of our existing code or test-cases, woo-hoo! You are exhorted to see the last problem on hw10-soln, to see how to avoid repeating any code between the two constructors.      

5If your grab calls drop, then the room will still also contain a lint.      

6If you have grab drop a lint, then there will be an additional lint lying on the floor.      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2007, Ian Barland, Radford University
Last modified 2007.Dec.14 (Fri)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme