Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Suppose we want to model the notion of a smart person who knows his/her birthday and can compute the number of months till his/her next birthday given the current month. For our purpose, a month can simply be represented by an integer, which in Java is called int. We start by writing "stub" code for the class Person that is to represent our smart person.

Code Block
class Person {
  /** 
   * Computes the number of months till the next birthday given the current month. 
   */
  intnMonthTillBD(intcurrentMonth) {
    // todo
  } 
}

Notice in the above there is really no concrete code. As a matter of fact, the above would not compile. Now we must abandon everything and start writing test code for nMonthTillBD(...).

...

  • Go to the File menu and select New Junit Test Case...
  • Create a stub test case called Test_Person. DrJava will create a stub class that looks like the following
    Code Block
    /** * A JUnit testcaseclass.
     * Every method starting with the word"test"will be called when running
     * the test with JUnit. */ 
    class Test_PersonextendsTestCase {
      /** * A test method.
       * (Replace"X"with a name describing the test. You may write as
       * many"testSomething"methods inthisclass as you wish, and each
       * one will be called when running JUnit overthisclass.)
       */
      void testX() { 
      } 
    }
    
    At this point, do not worry about what "extends TestCase" means in the above. DrJava is re-using the class TestCase from the JUnit framework in some clever way without you having to deal with all the details of how to use an existing class from some other files.

...

Now add the statement return 0; to the body of the method nMonthTillBD(...) and compile.

Code Block
class Person {
   int_bMonth; 

   /** 
    * Computes the number of months till the next birthday. 
    */intnMonthTillBD
   int nMonthTillBD(intcurrentMonth) {
      return0;// todo
   } 
}

Step 4.

After you have cleaned up your code for Person as shown in the above, you should be able to compile Test_Person. With Test_Person open, click on the Test button in DrJava tool bar.

...

Change the formula to

Code Block
intnMonthTillBD(intcurrentMonth   int nMonthTillBD(int currentMonth) {
       return_bMonth - currentMonth;// todo
   }

Compile all and test again.

...

Change the formula to

Code Block
intnMonthTillBD(intcurrentMonth   int nMonthTillBD(int currentMonth) {
      return(_bMonth - currentMonth + 12) % 12;// todo
   }

Compile all and test again. Now everything should pass! You may now remove the TO DO comment from the code of nMonthTillBD.

...