CS 99

Summer 2001                                                                                      7.26

 

 


Lab 9

 

Overview

The goals of this lab are to:

 

·         Complete the implementation of class Time and test its methods in a separate application called TimeTest.java

·         Modify class Time to include new methods, and test the new methods in a separate application called TimeIncrementTest.java.

·         Bonus part: Create a Pig Latin translator and test it in a class called PigLatin.java

 

Part I: class Time

This part seems longer than it actually is!  Take time to read the entire portion of this assignment before starting (you should always do that really).  And make sure you read carefully the code for class Time below.

 

Part A:

Complete the specifications for class Time below.  Class Time provides a way to store a time in minutes, seconds, and hours. Note the allowable values for the hour, minute, and second variables next to their definitions!  Save your class Time in a file called Time.java.

 

You must provide the code for the empty methods and constructors below.  There are 3 empty constructors and 8 empty methods.


Constructors (3)

The first constructor has been done for you.  You are well recommended to follow its example in completing the 3 remaining constructors.

 

Set Methods (3)

The set methods to be completed are setTime(), setMinute(), and setSecond().  setHour() has already been completed for you.  Follow its example for methods setMinute() and setSecond().  Use setHour(), setMinute(), and setSecond() judiciously in completing setTime().

 

Get Methods (3)

The three get methods to be completed--getHour(), getMinute(), and getSecond()--should be self-explanatory. 

 

String Methods (2)

Of the methods to be completed, these will require the most thinking.

 

toMilitaryString()
In Military time, 7:37:02AM is written as 07:37:02; 1:10:27PM is written as 13:10:27; and 11:56:59PM is written as 23:56:59.  Your toMilitaryString() method must use the hour, minute, and second variables of the Time object to create a String that returns the proper military time given by those values. So if the hour variable has value 7; the minute variable, value 37; and the second variable, value 2; the String should be "07:37:02".  Use String concatenation and if-else constructs to get the correct values in the String.

 

toString()

This method returns a String that represents the time in standard format.   You will need to use modulo arithmetic as well as String concatenation to make sure the time is represented properly because the hour variable can have any value from 0 to 23.  Append to the end of the String AM or PM as appropriate.

 

So if the hour variable has value 22; the minute variable, value 6; and the second variable, value 58; then the String should be "10:06:58PM".

 

 

class Time {
     private int hour;       /* 0-23 */

     private int minute;        /* 0-59 */

     private int second;       /* 0-59 */

 

/**

*    Default constructor for class Time

*    Initializes all the variables to zero.

*/

public Time() {

          setTime( 0, 0, 0 );

}

 

     /**

*    Construct a Time object given a time in hours

*    @param h  the time in hours

*/

public Time( int h ) {

 

}

    

/**

*    Construct a Time object given a time in hours and minutes

*    @param h   the hours
     *    @param m   the minutes

*/

public Time( int h, int m ) {

 

}

 

/**

*    Construct a Time object given a time in hours, minutes, and seconds

*    @param h   the hours
     *    @param m   the minutes
     *    @param s    the seconds

*/

public Time( int h, int m, int s ) {

 

}

 

// Set Methods
     /**
     *    Set a new Time value using military time.
     *    @param h    the hours
     *    @param m   the minutes
     *    @param s    the seconds
     */

public void setTime( int h, int m, int s ) {

 

 

}


     /**
     *    Set the hours.  Perform validity checks on the data.  Set invalid values to zero.
     *    @param h    the hours
     */

public void setHour( int h ) {

          if ( h >= 0 && h < 24 )
              hour = h;
          else
              hour = 0;

}

 

     /**
     *    Set the minutes.  Perform validity checks on the data.  Set invalid values to zero.
     *    @param m   the minutes
     */

public void setMinute( int m ) {

 

 

}

 

     /**
     *    Set the seconds.  Perform validity checks on the data.  Set invalid values to zero.
     *    @param s    the seconds
     */

public void setSeconds( int s ) {

 

}

 

// Get methods

     /**
     *    Return the hour.
     */

public int getHour() {

 

}

 

     /**
     *    Return the minute.
     */

public int getMinute() {

 

}

 

     /**
     *    Return the second.
     */

public int getSecond() {

 

}

     /**
     *    Convert the time to a String in military-time format.
     */

public String toMilitaryString(){

 

 

}


    
/**
     *    Convert the time to a String in standard-time format.
     */

public String toString() {

 

 

}

 

}

 

Part B:

Test your fully implemented Time class in a class called TimeTest.java.  We've helpfully provided the code for TimeTest.java below:

 

class TimeTest {

 

     public static void main( String[] args ) {

          TokenReader in = new TokenReader( System.in );
          String s = "y";

          int hours, mins, secs;

          Time t;

do {

              System.out.print("Enter an hour, minute, and second: ");

              hours = in.readInt();

              mins = in.readInt();

              secs = in.readInt();

              t = new Time( hours, mins, secs );

              System.out.println("Military Time: " + t.toMilitaryString() );

              System.out.println("Standard Time: " + t.toString() );

              System.out.println();

              System.out.print("Would you like to continue (y/n)? " );

              s = in.readString();

 

          } while( s.equalsIgnoreCase("y") );

 

 

     }

 

}

 

Test your code for the input values 18, 30, 22 for the hour, minute, and second respectively and for the input values 5, 14, and 59.  Cut and paste the output into a file called TimeTest.txt.

 

Part C:

Modify the Time class in Part A to include a method called tick() that increments the time stored in a Time object by one second.  Also provide the methods incrementMinute(), to increment the minute, and incrementHour(), to increment the hour.  The Time object should always remain in a consistent state.  Write a program called TimeIncrementTest.java to test these methods, to see if they're working correctly.  Be sure to test the following cases:

·         Incrementing into the next minute (e.g., 05:06:59AM to 05:07:00AM).

·         Incrementing into the next hour (e.g., 05:59:45AM to 06:00:45AM).

·         Incrementing into the next day (e.g., 11:59:59PM to 12:00:00AM).

 

Save your modified Time class in a new file called ModifiedTime.java.  Print that file as well as TimeIncrement.java.

 

Part II (BONUS):  Pig Latin Translator

This part does not need to be handed in at the next lab session, but may be handed in at the following lab session.  Those of you who feel that the exams are not a fair reflection of your knowledge in this course may use this bonus part to augment your grade in the course.

 

Write a program that accepts punctuation-less sentences from the user and converts them to their Pig Latin equivalents. The class that does this should be called PigLatin; save it in a file called PigLatin.java 

 

However, the task of converting English sentences to Pig Latin sentences should be handled by a separate class called PigLatinTranslator, saved in a file called PigLatinTranslator.java.

 

Part A:

Complete the specifications for class PigLatinTranslator below.

 

You should find the following String methods helpful:

·         startsWith                      Returns true if the current object starts with the specified string.
If s = "abcdefgh", then s.startsWith("ab") returns true, while s.startsWith("hi") returns false.

·         indexOf                          Used to locate the first occurrence of one string in another.
Characters in a string are indexed from zero starting with the leftmost character. If s = “abcdbc” then s.indexOf(“a”) yields 0, s.indexOf(“bc”) yields 1, and s.indexOf(“cb”) yields –1 because no occurrences are found.

·         substring                        Used to extract a contiguous portion of a string.
If i and j are integers then s.substring(i,j) yields a string that is made up of the characters in positions i thru j-1. Thus if s = “abcdef” then s.substring(3,4) yields “d”, s.substring(3,6) yields “def”, substring(3,3) yields the empty string, and s.substring(3,10) is an error.

·         concatenation             Used to “glue” one string to another.
If s1 =”ab”, s2 = “xyz”, and s3 = s2+s1+s2, then s3 references “xyzabxyz”.

·         toLowerCase               Converts all the characters in the String to their lower case equivalents.
If s = "My Name Is…", then s = s.toLowerCase() converts s to "my name is…".


One problem you will need to solve is how to break a String of words separated by spaces into individual Strings.  Fortunately, Java provides a way to do just that with the class StringTokenizer.  You must instantiate a StringTokenizer object with a String like so:

 

String sentence = "Chillin' in my 4.6 at the light."
StringTokenizer tokenizer = new StringTokenizer( sentence  );


You may find the following methods in class StringTokenizer useful:

 

·         nextToken                           Returns the next token in the String.
In the example above, if we write
String next = tokenizer.nextToken() immediately after declaring the tokenizer above, then "Chillin'" will be assigned to variable next. If we follow this statement by next  = tokenizer.nextToken(), next will now be assigned value "in". 

·         hasMoreTokens                Returns true if there are more tokens to be returned by the string 

tokenizer.

       In the example above, the following while loop

 

 

 

 

      while( tokenizer.hasMoreTokens() ) { 

System.out.println( tokenizer.nextToken() );

}

will print:

     Chillin'

in

my

4.6

at

the

light

 

·         countTokens                      Returns the number of tokens present in the string tokenizer.
In the example, if we write immediately after the declaration of the tokenizer,
System.out.println( tokenizer.countTokens() ), we will see 7 on the screen.  However, each time you use the nextToken() method, the remaining number of tokens decrements by 1.

Finally, the last thing you will need to know to finish the program: in method translateWord() when do we append the first letter of the word to the end and add "ay", and when do we append the first two letters to the end and add "ay"?  We append the first two letters if the word begins with any of the following prefixes:  bl, pl, br, pr, ch, sh, cl, sl, cr, sp, dr, sr, fl, st, fr, th, gl, tr, gr, wh, kl, wr, and ph.

 

You're ready to begin!

 

import java.util.StringTokenizer;

/* You must include the previous line if you use the StringTokenizer class! */

/**

*    class PigLatinTranslator represents a translation system from English to Pig Latin.
*/

class PigLatinTranslator {


/**
*    Translates a sentence of words into Pig Latin
*/

     public static String translate( String sentence ) {

     }

 

/**
*    Translates one word into Pig Latin.  If the word begins with a vowel, the suffix "yay"
*    is appended to the word.  Otherwise the first letter or two are moved to the end of the
*    word and "ay" is appended.
*/
private static String translateWord( String word ) {

}

/**
*    Determines if the specified word begins with a vowel.
*/
private static boolean beginsWithVowel( String word ) {

}

/**
*    Determines if the specified word begins with a particular two-character prefix.
*/
private static boolean beginsWithPrefix( String str ) {


}

 

}

 

 

Part B:

Use the methods you wrote in Part A to complete the following part. In method main of PigLatin write code so that the program will, when run, produce output that resembles the following:

 

Enter a sentence (no punctuation):
Do you speak Pig Latin

 

That sentence in Pig Latin is:
oday ouyay eakspay igpay atinlay

 

Translate another sentence (y/n)?  y

 

Enter a sentence (no punctuation):

Play it again Sam

 

That sentence in Pig Latin is:

agplay ityay againyay amsay

 

Translate another sentence (y/n)?  n

 

    Press Enter To Continue

 

 

Part III: Submitting the Lab

Hand in printouts for

 

·         Time.java

·         TimeTest.txt

·         ModifiedTime.java

·         TimeIncrementTest.java

 

For the bonus part, should you choose to do it, hand in printouts for

 

·         PigLatin.java

·         PigLatinTranslator.java

 

As usual, don't forget to put your name, net ID, and date at the top of each file.

 

This lab is due next Tuesday, 31 July 2001 at the beginning of the lab session.  Hand it in to Siddharth.

 

NOTE: The bonus part may be turned in August 2!