Intro Computer Math: Writing methods General Synax Methods

advertisement

Intro Computer Math: Writing methods

General Synax

Methods: public <return type> methodName ( parameter list )

Where <return type> specifies what your method will return to the calling method. We have currently used the following return types:

void – if you are not returning anything int – returning an integer boolean – returning true or false

The parameter list specifies what is the input to your method.

Instance methods: public void turnRight ( Robot r)

| | | | ----- parameter list

| | | ----------------- method name

| | ---------------------------- return type (int, double, String, void)

| -------------------------------------- access specifier (private or public)

Class methods:

public static int compute_sum ( int a, int b )

| | | | | ------ parameter list

| | | | ------------------- method name

| | | ------------------------------ return type

| | ------------------------------------ static for class method

| -------------------------------------------- access specifier

Instance methods belong to an object and need to be called with an object reference.

Examples include turnRight and turnAround, which belong to the Athelete class. To call turnRight, we first need to create an Athlete object and then we use the reference before the method.

For example:

Athlete karel = new Athlete(); karel.turnRight();

Static methods are class methods are not associated with an object. Class methods we have written are: takeTheField() and work_8x8_square(). Sometimes, you pass a reference to an object when you call the static method.

For example: we called takeTheField() with a Robot reference. So the method header was:

public static void takeTheField( Robot arg ) Note the static keyword.

All the www.codingbat.com examples are static methods because they do not belong to an object.

However, in order to automatically test your methods, they do create an object and associate your methods with a class, so that is why they are missing the static keyword.

When writing a method, the first steps you should take are:

1. Identify the input. What information do you need to perform this task.

2. Identify the output. What is your method going to return.

3. Come up with a meaningful method name. Make your code readable.

Examples

1. Your method will be passed 2 integer numbers and return the sum. input: 2 integers output: 1 integer method header: public static int sum( int a, int b)

The method will return an integer, so when I call it, I must store the result into an integer:

int x = sum (1, 2);

After the execution of this command, the value of 3 is stored into the variable x.

2. Your method will be passed 3 integer numbers and will return the largest value. input: 3 integers output: 1 integer method header: public static int max (int x, int y, int z)

The method will return an integer, so when I call it, I must store the result into an integer: int maxValue = max(9, -3, 16);

After the execution of this command, the value of 16 will be stored in the variable x.

3. Your method will return a boolean if the sum of the two numbers is within the range of 10-20. input: 2 integers output: boolean method header: public static boolean checkSum( int value1, int value2)

The method will return a boolean, so I can store it into a boolean or use it as a boolean expression. boolean result = checkSum(10, 5); or: if ( checkSum(12, 6) )

System.out.println(“within range”);

You Try

1. Your method will be passed 2 integers and will return the difference. input: output: method header:

How will you call this method:

2. Your method will be passed 2 boolean values and will return the result of the AND operation. input: output: method header:

Give an example of how will you call this method:

3. From www.codingbat.com

The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return true if we sleep in. input: output: method header:

Give an example of how you will call this method:

4. Given 2 integer values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative. input: output: method header:

Give an example of how you would call this method:

Writing the body of a method:

You need to know the syntax when writing methods. Here are some commonly used operators.

Arithmetic operators

Operator

+

-

*

/

Meaning add subtract multiply divide mod (remainder)

Example count = count + 1; profit = earnings – cost; volume = width * height * length; average = total / num; if (x % 2 == 0) // if even %

Relational Operators

Operator

==

!=

>= and >

<= and <

Meaning equal to not equal to greater than less than

Example if (n == 3) if (n != 3) if (n > 3) if (n < 3)

Assignment Operator

Operator

=

Meaning assignment

Example x = 2;

Logical operators

Operator

&&

||

!

Meaning

AND

OR not

Control if (boolean condition) do_something_a(); else if (boolean condition) do_something_b(); else do_something_c();

Example if (hasBeepers && (count > 1)) if (rightIsClear || frontIsClear) if (!found)

Note: if the body within an if statement is more than 1 statement, you need to enclose them with curly braces { .. } . Example: if (nextToABeeper())

{

count = count + 1;

pickBeeper();

}

Common statements:

1. Test for a range: if x within the range of 10 and 20

if ( x >= 10 && x <= 20) //note, you need 2 separate statements

// you cannot use: 10 <= x <= 20

2. Test multiple conditions: test isMorning AND hour is greater than 7 if (isMorning && hour > 7)

3. Use the % (mod) operator to get the remainder.

Note: x % 10 returns the remainder after dividing x by 10

Examples:

22 % 10 => 2 because 22/10 is: 2 r 2

22 % 7 => 1 because 22/7 is: 3 r 1

99 % 10 => 9

135 % 25 => 10

Return statements:

If your method returns a data type (examples: integer, double, boolean, or String) your method is required to specify the return type in the method header (see above) and use the return keyword to pass back the value to the calling method.

For example: In the method above where we returned the sum of 2 integers:

The compete method is: public static int sum( int a, int b)

{

} return a + b;

The variable or value returned must match up with the <return type> defined in the method header.

You try:

1. Write a method with 2 parameters: isWeekend and hour. Return true if you are in school at the specified hour.

input: output: method

2. You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an integer value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. input: output: method:

3. Given a number n, return true if n is in the range 1..10, inclusive. Unless "outsideMode" is true, in which case return true if the number is less or equal to 1, or greater or equal to

10. input: output: method:

Loops:

There are 2 types of loops we will learn about in this class; for loops and while loops. You can always use either one, but typically a for loop is used when you know how many iterations (times you will repeat within the loop). A while loop is used when it the termination condition is dependent on a condition, like nextToABeeper().

The syntax for these loops are as follows:

Note: You need to know how to write both loops from memorization. After practicing it for a while, it will come naturally.

for ( initialization ; boolean termination condition ; update statement)

{

}

//body of loop

Example:

for (int k=0; k < count; k++)

{

r.putBeeper();

r.move();

}

while ( boolean termination condition)

{

//body of loop

}

Example: while (nextToABeeper () )

{

pickBeeper( );

}

1. Write a loop to pick up a pile of beepers. Maintain a count of how many you picked up.

2. Write a loop to put down 10 beepers.

3. Write a loop to put down count beepers, where count is a variable that has already been declared and initialized.

4. Declare a count and initialize to 0. Pick up a pile of beepers, incrementing count. Then put back down half of them.

5. Put down 5 piles of 3 beepers, move 2 spaces between piles.

Download