Using Loops, Arrays, Methods to do stuff in Java
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
for y
from 0
to H
{
for x
from 0
to W
{
if (x
,y
) is part of the circle {
print "*"
}
else {
print " "
}
jump to the next line
}
}
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
in our display?
R - line_width
≤ x^2 + y^2 ≤ R + line_width
for y
from 0
to H
{
for x
from 0
to W
{
if (x
,y
) is within line_width
from the circle {
print "*"
}
else {
print " "
}
jump to the next line
}
}
Drawing a circle centered at (a
, b
)
(x - a
)^2 + (y - b
)^2 = R
Drawing a circle centered at (a
, b
)
(x - a
)^2 + (y - b
)^2 = R
Let's try swapping the values of variables
Let's try swapping the values of variables
Let's try swapping the values of variables
Let's try swapping the values of variables inside a method
Memory addresses
Passing primitive variables
When we pass primitive types as arguments to a method, we are passing copies of the arguments. So the value of the original variables cannot be changed inside a method
Arrays are a reference type
Arrays are a reference type
Passing array variables (reference types )
When we pass reference types as arguments to a method, we are passing the memory address of the arguments. So the values of the original variables CAN be changed inside a method
/