/* MethodExamples.java example code AC Chapin */ package cis119.pkg11.methods; public class MethodExamples { // prints out its arguments in order // the keyword static is needed because this is called by main // without creating an instance first public static void printParams(int i, double d, String s, boolean b) { System.out.println("First argument: " + i); System.out.println("Second argument: " + d); System.out.println("Third argument: " + s); System.out.println("Fourth argument: " + b); } // return the average of the given five ints public static double average(int a, int b, int c, int d, int e) { // creating a result in a local variable, then returning it double result = (a + b + c + d + e)/5.0; return result; } // return the plural by adding s public static String pluralize(String str) { // creating the result right in the return statement return str + "s"; } public static boolean divByFive(int n) { return n % 5 == 0; // does same thing /* if(n % 5 == 0) { return true; } return false; */ } // set up a Bunny with the given name and carrot count public static Bunny makeBunny(String name, int count) { Bunny tempBunny = new Bunny(); tempBunny.name = name; tempBunny.carrotCount = count; return tempBunny; } // have the cat eat the bunny, if it is hungry. public static void carnivoreTime(Cat predator, Bunny prey) { if (predator.hungry) { predator.eat(prey); } else { System.out.println(predator + " just plays with " + prey); } } // call the methods public static void main(String[] args) { // literal arguments printParams(7, 2.5, "hello", true); // variable arguments int x = 3; double b = 3.3; String str = "goodbye"; boolean q = false; printParams(x, b, str, q); // putting return value in a variable, then printing double r = average(1, 2, 3, 4, 5); System.out.println("average: " + r); // printing return value directly System.out.println(average(10, 20, 30, 40, 50)); // using return value in expression System.out.println("plural of cat is " + pluralize("cat")); Cat kitty = new Cat(); kitty.name = "Kittyface"; kitty.hungry = true; Bunny bun = new Bunny(); bun.name = "Mr. Bun"; carnivoreTime(kitty, bun); // first argument is Cat address without variable name // makeBunny returns a Bunny address carnivoreTime(new Cat(), makeBunny("Harvey", 17)); // note that the null printed in this case is the // cat's name, since that never got set in this case. } }