Methods Practice

Methods Practice

Methods practice

EXAMPLE showing method definition and how that method is called from the main code.
Main code:
public static void main(String[] args) {

double ans = power(5,3);//this finds 5 to the power of 3. .: it returns 125.
...

}
//method definition:
// It is called power(), it takes two ints and sends back a double.
static double power(int base, int exponent) { }

In these 5 questions you either have
(i) an example of a method definition and have to write how you would call the method, or
(ii) you have an example of how the method it called, and you have to write the definition.

  1. Here is the definition of a (fake) method:
    /* This method prints out the text, and then prints a line of === under it. */
    void underline(String text) {}

Write the code to call this method with the text "Unit 3: Methods and Arrays".

  1. Here is the definition of a (fake) method:

/* This method adds ‘s’ or ‘es’ to a word if n is more than 1.
It returns the word, pluralized if necessary.*/
String addPluralToWord(double n, String word) {}

a)Write the code to call this method with “book” and “3”.

b)Use this method to print out “I saw 4 buses” (pass bus and 4 to the method and use the result)

  1. Given this code, write the method definition for the reverse method:

public static void main(String[] args) {

String newWord = reverse("Hello");
}

  1. Given the following code, write the method definition for coneVolume():
    public static void main(String[] args) {
    double vol = coneVolume(3.8, 2.0);
    System.out.printf("The volume of the cone is %f", vol);
    }
  1. Pretend that there is a method called shortWord() that takes a word and returns true if the word is 4 letters or less.

a)Write the method definition (which sometimes I call method header) for shortWord().

b)Write a few lines of code to call this method with some word, and then print out if the word is short or not.

  1. a) Look up the method definition for Math.toDegrees(). Copy it down here.
    b) Write a line or two of code to use it in a program.