Vous êtes sur la page 1sur 46

Newport Robotics Group

Fundamentals of ObjectOriented Robot Programming in


Java
Day 3
10/9/2014

T/Th, 6:30 8:30 PM


Big Picture School

Day 1 Review Exercise


Display
Display

the sum of 4 numbers


the remainder when the sum is
divided by 3

Object-Oriented Programming
(OOP)
Object

Oriented Programming (OOP) is a


methodology that breaks programs into
discrete, reusable units of code called
objects which attempt to model things in
the real world
Class Blueprint that defines properties
and behaviors applying to a set of objects
Object A specific instance of a class

But what does a class do?


A class defines 3 things about a type of
object:
Instance Fields - Information the object
contains (data)
Methods - What the object does
Constructors - How the object is made

What does the code look like?


Code

is a series of keywords and


instructions that tell the computer what to
do
In Java, whitespace does not tell the
computer to stop doing something,
although you need at least one space
between keywords
Generally, we put each statement on its own

line to make it easy to read

semicolon at the end of a statement tells


the compiler where the statement ends;

Primitive Types
boolean

true or false (Is the cow

awake?)
int an integer (How many spots on a
cow?)
double a precise floating-point number
(How many pounds does the cow weigh?)
Others

float less-precise floating-point number


char a text character, such as: a $ 6
A few more we probably dont need to know

Variables
We

use variables to store data in the


computers memory
Before we can use a variable, we must
declare it to the compiler
A declaration consists of a data type and a
variable name (plus a semicolon).
Examples:
boolean awake;
int spots;

camelCase
When

naming things in Java, we have to


keep things as one word
Generally, it is best if variable names are
as descriptive as possible
For variables, leave the 1st letter
lowercase
Capitalize the 1st letter of each word
This system is called camelCase (for the
hump at the beginning of each word)
Example: robotPositionOnField

Default Values
Once

you declare a variable with a


primitive type, it contains its default value

Default

values:

boolean: false
int: 0
double: 0.0
float: 0.0f
(f indicates its a float and not a double)

Assignment
Once we have a variable, we can use it!
Use the equals sign (=) to assign a value

on the right to a variable on the left

int studentCount;
studentCount = 17;
Now studentCount holds the value 17!

Initialization
Declaring

a variable and then setting its value


is tedious. We can do this faster on one line:

int studentCount;
studentCount = 17;
int studentCount = 17;
These two statements are equivalent!
When you declare a variable, you should almost
always initialize it right away.

What if I want to explain my


code?
We can explain what code does or make notes
about it using comments
Code after two slashes (//) will be ignored by the
Java compiler if it is on the same line
Any code between /* and */ will be ignored, even if
it is on multiple lines.

Example:
x = 2; /* This is a multi-line
comment explaining my code. */
y = 3; // Here is a single-line comment.
b = true;

Comparison Operators
Output boolean
Equality: ==

values true or false

Greater than: >


Less than: <
Greater than or equal:
Less than or equal: <=
Not

equal: !=

>=

Boolean Operators
AND

OR

&& ||
true &&
true ==
true
true &&
false
==
false
false
&& true
==
false

true ||
true ==
true
true ||
false
== true
NOT

false
|| true
== true

!true == false

Math Operators
Addition +
Subtraction

Multiplication *
Division /
Remainder of Division %
Increment (add 1) ++
Decrement (subtract 1)

--

Assignment/Math Operators
To

add 6 to a number, we could write:

int x = 5;
x = x + 6;

Or

we could use the += operator:

int x = 5;
x += 6;

adds a number at right to the value of x


and stores the result back in the variable x
A similar thing is true for -=, *=, /=, and
%=
+=

Strings
A group of characters (chars) that form
Use quotation marks to make a String

text

Example:

The quick brown fox


jumps over the lazy dog.

You

can display a String on the screen using


System.out.println(show this);

The main Method


When

you run a program, the first thing that


happens is the main method runs
Code between the curly braces will be
executed
Dont worry about the details of the first
line it will make more sense later (and
Eclipse will automatically generate it for
you)
public static void main(String[] args)
{
// ...Code you put here will run!

Sample Code
This

code will compute the sum of three


integers and print it on the screen.

int a = 5;
int b = 7;
int c = -1;
int sum = a + b + c;
System.out.println(sum);

Where we left off

Your Turn
Write

code that does the following:

Declares two integer variables


Initializes the two variables
Declares a variable to hold an average
Assigns the average of the two integers to the

average variable
Prints the result

A Possible Solution
int a = 1;
int b = 4;
double average = (a + b) / 2.0;
System.out.println(average);

Methods

Organize our codes functions

What is a method?
method is a block of code that performs
some operation
Think of it as a machine that both inputs
and outputs data
A

accessor method provides access to


data
A mutator method changes data
An

Methods
Think

of a method from our earlier


example: We need to find the average of
two integers.
What are the inputs of the method?
What is the output of the method?
What does the method do?
What is the method called?

Method Name
A

method name must describe what the


method does accurately and succinctly
Use camelCase starting with a lowercase
letter
Example:

sumOfThreeInts

Parameters
to a method are called parameters
or arguments
Just as before, we need to tell the
compiler what data types the parameters
are by declaring them
Separate parameters by commas
Inputs

Example:

int a, int b

Return Type
When

a method outputs a value, we say


that it returns that value
We must specify to the compiler what
data type the method outputs
This is called the return type
If

a method has no output, its return type


is called void

Access Modifiers
method should specify an access
modifier to control who can use the
method
The most common access modifiers are
public and private
Public methods can be used by anyone
Private methods can only be used
internally
Example: In an ATM machine, the method
enterPIN should be public (users can
press buttons), but the method
A

Method Signature
method signature is the first line of
any method and tells the compiler what
the method does
The method body, or code that runs when
the method is used, must follow the
contract set up by the method signature
Example: if the signature says that the
method outputs an int, the body cannot
output a boolean.
The

Method Signature
We

can make a method signature by putting


the following parts together:
Access Modifier
Return Type
Method Name
Parameters (in parentheses)

If there are no parameters, use empty parentheses (). Do not put


void.

Example:
public int sumOfThreeInts(int a, int b, int c)
Access
Modifier

Return
Type

Method
Name

Parameter
s

Method Body
The

body of the method is a block of code


between two curly braces
The method body uses the inputs and
generates the output
The return statement indicates the output
public int sumOfThreeInts(int a, int b, int c)
{
Method
Signature
// ...(Method body goes here)
return something; //something is an int
}

Implementation
When

we write the code for a method, we


say that we implement that method

public int sumOfThreeInts(int a, int b, int c)


{
int sum = a + b + c;
Implementation
return sum;
}

Calling Methods
Now

we have created our method, or


machine. However, just because it knows
what to do doesnt mean it gets used
Example: A washing machine may have all the

code it needs to run, but nothing will happen


until the user puts clothes in and turns it on

To

make a method run, we call it.

How to Call a Method


To

call a method, put the method name


and values for any parameters in
parentheses
Example: sumOfThreeInts(5, 2, 1)
In this case, the method will run with a having a
value of 5, b with a value of 2, and c with a value
of 1.

However, we dont do anything with the


value the method returns in this case

Using a Method Call


We

can make use of method calls by


storing their return values in a variable.

Example:

int x = sumOfThreeInts(1, 4, -3);

In this example, after the line of code runs, x


will have a value of 2.

Any Questions?
Before you try it?

Implement Your First Method


Write

the method for the average of two


integers complete with a method
signature and implementation.
Call your method from the main method.
Store the return value from your method
in a variable you declare in main
Print out the return value from your
method at the end of the main method.

Possible Solution
public double average(int a, int b){
double a = a+b;
a = a/2;
return a;
}
public static void main(String[] args){
System.out.println(average(6,9));
//prints out 7.5
}

Lets Turn it up a Notch


Write

a program that takes in 3 doubles


and returns in the difference between the
mean and the sum.
Call your method from main(String[] args)

Possible Solution
public double a(double a, double b, double c){
return (a+b+c)*2.0/3.0;
}
public static void main(String[] args){
System.out.println(a(5.5,7.5,9));
}

Lets turn it up a Notch


(Challenge)
Write

a program that takes in 2 integers


and returns the larger.
No if statements.
Can use Math in javas library

Possible Solution
public static int(int a, int b){
return(Math.abs(a-b)+a+b)/2;
}

Lets Turn it up (Bigger Challenge)


Extend

the problem to a method that


takes in an array of integers and returns
the largest one.

Possible Solution
public static int max(int[] a, int i){
if(i == 1){
return(Math.abs(a[0]-a[1])+a[0]+a[1]);
}
int[] b = new int[2];
b[0] = a[i];
b[1] = max(a,i-1);
return max(b,1);
}

Lets Turn it up some more


(Even Bigger Challenge)
Write

a method that takes in an integer n,


and outputs all the reduced fractions from
0 to 1 in increasing order with
denominator less than or equal to n.