Using Loops, Arrays, Methods to do stuff in Java
Methods
Think of methods as machines that take some input and produce some output
Methods are defined by their input and their output
Methods
Think of methods as machines that take some input and produce some output
You can also think of them as mathematical functions
Methods are defined by their input and their output
Methods
Think of methods as machines that take some input and produce some output
You can also think of them as mathematical functions
Methods are defined by their input and their output
Methods in Java
Methods in Java are defined by:
- A name
- An input type
- An output type
Methods in Java
Methods in Java are defined by:
- A name
- An input type (
int x
)
- An output type (
return x*x;
)
Methods in Java
Methods in Java are defined by:
- A name
- An set of input types (
int x, int y
)
- A single output type (
int
, return x*x;
)
Methods in Java
Methods in Java are defined by:
- A name
- An set of input types (
String[] args
)
- The empty return type (
void
)
A method that checks if a number is prime
Methods in Java are defined by:
- A name
- An set of input types (
int n
)
- A single output type (
int
, return answer;
)
A method that prints the first N primes
Methods in Java are defined by:
- A name
- An set of input types (
int N
)
- A single output type (
void
)
An application: Generating random rumbers
Please, take a look at the code here
Random numbers in Java
Let's write a simple game with the following rules:
- The player picks a maximum number
N
- The computer picks a random number between
1
and N
- The player has 10 tries to guess the number
Random numbers in Java
Let's write a simple game with the following rules:
- The player picks a maximum number
N
- The computer picks a random number
R
, between 1
and N
- The player has 10 tries to guess the number:
Let's add another rule:
- If the player's guess is smaller than
R
, print "Too small"
- If the player's guess is bigger than
R
, print "Too big"
Another application: A simplsitic version of computer displays
How can we display images on computer displays?
How can we display images on computer displays?
Every cell in the grid is called a pixel
Pixel : Picture element
Pixel coordinates on a display
Changing coordinate origin to the center of the screen
Changing coordinate origin to the center of the screen
Let's emulate a computer display with the Java console
Our display will only have two "colors"
-
*
: represents a black pixel
-
: the whitespace character representa a white pixel
How do we draw a circle of radius R
in our display?
x^2 + y^2 = R
How do we draw a circle of radius R
in our display?
x^2 + y^2 = R
Since our display is discrete we will have to be more forgiving
R - line_width
≤ x^2 + y^2 ≤ R + line_width
How do we draw a circle of radius R
centered at (a
, b
) in our display?
(x - a
)^2 + (y - b
)^2 = R
/