Methods


Methods

Bunny.java

Cat.java

MethodExamples.java


Classwork

Pay attention to what you are being asked to pass to and return from methods. Passing is not the same as reading from a user. Returning is not the same as printing.  Extra local variables inside these methods will make many of these tasks easier and in some cases are necessary.


Create a project using the usual naming convention.

Part A

Put the following methods in a class with a main. Use the keyword static after public for each method.

Write a method named even which takes an int as parameter and returns true if the int is even, and false otherwise. 

Write a method named findOdd which takes an int as parameter.  Use the even method you just wrote as a tool to determine whether this parameter is even or odd.  As long as it is even, repeatedly divide by two; as soon as you are down to an odd, return that. 

So findOdd(17) would return 17, and findOdd(56) would return 7 ( since 56/2=28, 28/2=14, 14/2= 7)

Write a method repeater which takes  two parameters, a String and an int.  Return a String which consists of the String parameter repeated the number of times given by the int. (hint: we are returning, not printing; think about how we stick strings together)

So repeater("hello", 7) would return "hellohellohellohellohellohellohello";

Test these by calling them from main.


Part B

Add Cat.java and Bunny.java to your project (you will need to fix the package statements). 

The following methods go in the class with main, and like main should be static.

☑ Add a method makeKitty which takes a String name and returns a Cat.  In the method, create a Cat, set its name using the String given, call its miaow method, then return it.

☑ Add a method feedTheKitty, which takes a Cat and returns nothing.  In this method, create a Bunny, name the Bunny "Dinner", and then feed it to the Cat using the Cat's eat method.

[EC] first check that the Cat we were passed is not null, and if it is, complain that we can't feed a nonexistent Cat and don't do the rest.

In your main, test these by using a call to makeKitty as the argument you pass to feedTheKitty

[EC] Add a method biggerBun which takes two Bunnys.  It returns whichever Bunny has higher carrotCount.  If they had the same carrotCount, it doesn't matter which you return.  If one of the Bunnys is null, the other is automatically bigger, if both are null just return null.  Test this in main.