(ε-faster than slow motion)
Last class we saw what happens if we do things like
We can force our program to treat a number as having a different type
(TYPE
)variable_name
Forcing java to treat a double
as an int
Forcing java to treat a int
as an double
while
( logical_expression )
do something;
false
false
, the program never stops
An infinite loop
while
( there are apples left in the box )
do something;
while
( there are apples left in the box ){
if
( the apple is not rotten )
then
it goes in one of the shelves;
else
then
it goes in the garbage bin;
}
A friend wants to come visit Montreal
Your friend wants to come when the weather is nice
We will use a computer program to help us decide the best time
Arrays provide a way of holding more than one value with the same variable name
The values in the arrays are of the same type
If we know the size but not the content of the array
TYPE[]
variable_name = new TYPE[
N];
If we know the content of the array
TYPE[]
variable_name = {
VALUE_1,VALUE_2, ..., VALUE_N};
int
: the type of the array
[]
: this variable is an array
days_per_month
: the variable name
{31,28,31,30,31,30,31,31,30 31,30,31}
: The content of the array
int
: the type of the array
[]
: this variable is an array
days_per_month
: the variable name
new int
: Allocating memory on the computer for this array
[12]
: The length of the array (number of elements)
The usual way of using arrays is to do something for
every element in the array
0
. The last element of an array with n
elements is at position n-1
for
(TYPE
element_name: array_name ){
do something with element_name;
}
for
each element in array_name, do something
for
(initialize_index; logical_expression; change_index_value){
do something;
}
initialize_index;
while
( logical_expression ){
do something;
change_index_value;
}
The file Example6_Calendar.java shows how to use it, to get monthly temperature data
Using loops only:
n
/