Pretend for a moment that the method is already defined. Write down two or more expressions that use this method (in correct Java syntax, so that if it were already defined, you could type them in and get answers), along with the "right answer" you expect each example to produce. This step is useful in at least three ways.
Start with the simplest possible examples, then work up to more and more complicated examples. For now, we'll write these as comments:
/** * cube : find the third power of a number. * * @param num the int to be cubed * @return the number num^3, which is also an int */ /* MyClass.cube(0) should be 0 MyClass.cube(5) should be 125 MyClass.cube(-4) should be -64 MyClass.cube(MyClass.cube(3)) should be 19683 */
/** * howOld : produce a formatted message showing a person's name and how * old (s)he is. * * @param name a String indicating the person's name * @param age an int indicating the person's age in years * @return a String, something like "Joe Schmoe is 21 years old." */ /* MyClass.howOld("Steve", 45) should be "Steve is 45 years old." MyClass.howOld("Bob", 22) should be "Bob is 22 years old." */
Note that every Java method "lives in" a class,
and you need to specify the class when you call the method. The above
examples assume that the methods live in a class named
MyClass
.
The problem with writing examples in a comment is that you still have to type them into the CodePad and check whether the answers match what you said they should be. In a few days, we'll see a more convenient way to write test cases.