Next: None. Up: Expressions and loops. Previous: The while statement.


Using methods

Textbook: Section 2.9

A method defines some actions to accomplish for a given set of inputs. These inputs are called arguments.

We've been using one method named IO.println quite a bit already.

IO.println(42);
IO.println takes a single argument - some piece of data which is to be displayed into the I/O window. In this case, the argument is the integer 42.

Java includes a variety of methods, split between many classes. For example, the Math class includes a method called Math.pow, which takes two double arguments and computes the first argument raised to the power of the second. This method has a return value - in this case, the result of the computation, which is itself a double.

double x = Math.pow(16.0, 0.5);
In this example, the computer computes 16.00.5 - that is, the square root of 16.0, which is 4.0. So 4.0 is what goes into the x variable.

You can call methods within expressions however you want.

IO.println(Math.pow(y + 1.0, 2.0) + Math.pow(y - 1.0, 2.0));
If y held the value 3, this would compute (3+1)2 + (3-1)2, and it would print that value (20.0) to the I/O window.

The Math class holds a variety of useful methods. You can read about them in the Java library documentation. You'll be using the library documentation quite a bit throughout this course, so it's good to get used to it now. There's a link on the CS160 Web page directly to it.

The IO class also holds many useful methods. We've been using the IO.print and IO.println methods already. But there are also methods for reading numbers from the user. For example, IO.readInt() will wait until the user types a number, followed by the Enter key, and then it will return the int value the user typed. The IO.readDouble() method works similarly.

Here's a program that converts Celsius temperatures typed by the user into Fahrenheit.

import csbsju.cs160.*;

public class Example {
    public static void run() {
        while(true) {
            IO.print("Celsius: ");
            double celsius = IO.readDouble();
            IO.print("Fahrenheit: ");
            IO.println(1.8 * celsius + 32);
        }
    }
}
If I ran this, then it would work as follows. (Boldface indicates characters the user typed.)
Celsius: 0
Fahrenheit: 32.0
Celsius: -40
Fahrenheit: -40.0
Celsius: 37.0
Fahrenheit: 98.6
Celsius: and so on
Since the while condition is always true, this program actually never quits; it will keep asking for more temperatures to convert until the window is closed (or somebody pulls the plug).


Next: None. Up: Expressions and loops. Previous: The while statement.