Transcript Lec8.ppt

This week in CS 5
A dizzying array
of possibilities...
• HW 9 (2 problems)
due Sunday, 11/4 at midnight
M/T sections
due Monday, 11/5 at midnight
W/Th sections
Reading: Week 9’s online notes
Recitation for HW9 -- Friday 11/2
John Conway
This week’s honorees
are truly frightening...
Carl Gauss
“Pass By Value”
public static void main(String[] args)
{
int age = 18;
H.out.print(“After a semester at HMC, you’ll feel ”);
change(age);
H.out.println(age + “ years old.”);
}
public static void change(int age)
{
age = 42;
PASS
BY
VALUE
return;
}
“Pass by value” means that data is copied when sent to a method
Passing Arrays by Value
public static void main(String[] args)
{
int[] age = new int[2];
age[0] = 18; age[1] = 19;
H.out.print(“After a semester at HMC, you’ll feel ”);
change(age);
H.out.println(age[0] + “ or ” + age[1] + “ years old.”);
}
public static void change(int[] age)
{
age[0] = 42; age[1] = 42;
return;
}
Watch out!
public static void main(String[] args)
{
int[] age = new int[2];
age[0] = 18; age[1] = 19;
H.out.print(“After a semester at HMC, you’ll feel ”);
change(age);
H.out.println(age[0] + “ years old.”);
}
public static void change(int[] age)
{
age = new int[2];
age[0] = 42; age[1] = 42;
return;
}
Arrays and Methods
Engineers think their equations are an approximation to reality.
Physicists think reality is an approximation to their equations.
Mathematicians don't care.
Simple Facts > build
structures from
them
Simple Actions
(computations)
-> build
structures from
them
2d arrays
Arrays can be of ANY type -- even other arrays!
double[] arr;
double[][] arr;
arr = new double[nRows][nCols];
arr[0][2] = 10.0;
2d arrays: Input and Output
public static void main(String[] args)
{
double[][] arr = new int[3][4];
// getting the array
for (int r=0 ; r<3 ;
{
for (int c=0 ; c<4
{
bigarray[r][c] =
}
}
from input
++r)
; ++c)
H.in.nextDouble();
Using 2d arrays
picture before & picture after -- fill in the code...
Problem 1
An array of different methods...
Initial Input
Get the number of stock prices from the user
Create an array of the appropriate number of elements.
Then, get each stock price from the user into the array.
Menu
1 Display prices
2 Compute average of prices
3 Compute variance of prices
4 Display index and value of lowest price
5 Display index and value of highest price
6 Your TTS investment strategy
9 Quit
Which choice would you like?
Problem 1
How do we do this ? Pseudocode...
Methods
What does this code do ?
public static void main(String[] args)
{
}
public static double sumArray(double[] arr)
{
double sum = 2.0;
sum = sum + 40.0;
return sum;
}
Calling Methods
What happens back in main()?
Method notes
double averageArray(double[] arr)
double variance(double[] arr)
int indexOfSmallest(double[] arr)
int indexOfLargest(double[] arr)
Problem 2
on
on
off
off
off
on
A starting row of lights
0
1
2
3
4
5
Each turn, a light is selected -It and its neighbors switch states.
2 is selected
0
1
2
3
4
5
0
1
2
3
4
5
Goal: get all the lights off…
Problem 2
What is a light ?
on
on
off
off
off
on
How should we represent
these lights in Java ?
0
1
2
3
4
5
Lights Out -- Printing
// draw the current set of lights
0
“on” lights
should be 4x4
blocks of stars
|
|
|
|
2
1
3
4
|****|****|****|
|****|****|****|
|****|****|****|
|****|****|****|
0
“off” lights should be
4x4 blocks of spaces
1
2
3
print light numbers close
to the center of each light
lights should be
separated with
vertical bars
5
|****|
|****|
|****|
|****|
4
5
6
7
may display all light
numbers up to 15
Arrays in pictures
H.out.println(“Type the number of words:
int len = H.in.nextInt();
String[] quip;
quip = new String[len];
”);
5
int len
quip[1]
quip[3]
quip[0]
quip[2]
quip[4]
String[]
quip
for (int i=0 ; i<len ; ++i)
{
quip[i] = H.in.nextWord();
}
for (int i=len-1 ; i>=0 ; --i)
{
H.out.print( quip[i] + “ ” ); i is 4
i is 3
i is 1
i is 0
i is 2
}
fall leaves after leaves fall
public static int numSyllables(String w)
{
int numSyls = 0;
int len = w.length();
if ( isVowel(w.charAt(0)) )
++numSyls;
Syllable
counting
// an initial vowel ?
for (int i=1 ; i<w.length() ; ++i)
{
// vowel preceded by a consonant
if ( isVowel(w.charAt(i))&& !isVowel(w.charAt(i-1)) )
++numSyls;
}
// final ‘e’ preceded by a consonant
if ( w.charAt(len-1) == 'e’
&&
len >= 2
&&
!isVowel(w.charAt(len-2))
)
--numSyls;
if (numSyls < 1)
numSyls = 1;
return numSyls;
}
// every word has at least 1 syllable
A puzzle...
Take in a number of words and print them out in reverse order.
(To be specific, suppose it’s 5 words.)
A puzzle...
Take in a number of words and print them out in reverse order.
(To be specific, suppose it’s 5 words.)
String
String
String
String
String
s1
s2
s3
s4
s5
=
=
=
=
=
H.in.nextWord();
H.in.nextWord();
H.in.nextWord();
H.in.nextWord();
H.in.nextWord();
H.out.print(
H.out.print(
H.out.print(
H.out.print(
H.out.print(
s5
s4
s3
s2
s1
+
+
+
+
+
“ ” );
“ ” );
“ ” );
“ ” );
“\n” );
Not a very flexible solution...
Arrays - lists of data items
declares a String
array named quip
String[] quip;
quip = new String[5];
declares five Strings named
quip[0]…quip[4]
for (int i=0 ; i<5 ; ++i)
{
quip[i] = H.in.nextWord();
}
index
loop through
the array
Arrays in code
H.out.println(“Type the number of words:
int len = H.in.nextInt();
String[] quip;
quip = new String[len];
for (int i=0 ; i<len ; ++i)
{
quip[i] = H.in.nextWord();
}
”);
// create an empty array
// create array elements
// input each element
// now print them out in reverse order…
Sentence palindromes
fall leaves after leaves fall
bores are people that say that people are bores
First Ladies rule the state and state the rule, “Ladies First!”
you can cage a swallow, can’t you, but you can’t swallow a cage, can you?
Arrays
Element types
Example
Declaration
vs
Strings
double, int, String,
boolean, char, (any type) …
char
double[] arr;
arr = new double[100];
String s;
The ith element
arr[i]
s.charAt(i)
Length
arr.length
s.length()
Range
Warning
from
0
up to
length-1
Be careful not to go out of bounds!
java.lang.StringIndexOutOfBoundsException: -1
java.lang.ArrayIndexOutOfBoundsException: -1
T. T. Securities
Input stock prices for a number of days in a row,
and then analyze that data… .
Menu:
1 Display prices
2 Compute average of prices
3 Compute standard deviation of prices
4 Display index and value of lowest price
5 Display index and value of highest price
6 Your TTS investment strategy
9 Quit
Which choice would you like?
Arrays and Methods
public static double sumArray(double[] arr)
Using sumArray
public static void main(String[] args)
{
// prompt for and input nStocks
double[] stocks = new double[nStocks];
// input and assign each stocks[i]
double stockSum = sumArray(stocks);
H.out.println(“The sum is ” + stockSum);
}
double[]
stocks
90.0
10.0
60.0
42.0
public static double sumArray(double[] arr)
{
// see previous page …
return sum;
}
75.0
double[]
arr
70.0
Using sumArray
public static void main(String[] args)
{
// prompt for and input nStocks
double[] stocks = new double[nStocks];
// input and assign each stocks[i]
double stockSum = sumArray(stocks);
H.out.println(“The sum is ” + stockSum);
}
double[]
stocks
90.0
10.0
60.0
42.0
75.0
2 references referring
to the same list of data
public static double sumArray(double[] arr)
{
// see previous page …
return sum;
}
double[]
arr
70.0
Array Searching
public static double findMax(double[] arr)
T. T. Securities
Find the most profitable strategy for buying and
selling the stock among the prices in the array...
Day
Day
Day
Day
Day
Day
0
1
2
3
4
5
Price
Price
Price
Price
Price
Price
is
is
is
is
is
is
90.0
10.0
60.0
42.0
75.0
70.0
Lights Out !
on
on
off
off
off
on
A starting row of lights
0
1
2
3
4
5
Each turn, a light is selected -It and its neighbors switch states.
2 is selected
0
1
2
3
4
5
0
1
2
3
4
5
Goal: get all the lights off…
Lights Out !
Features of the game:
// allow the user to set the
//
number of lights from 3 to 15
// start each light randomly on or off
// draw the current set of lights
// allow the user to select a light
//
only allow valid lights !
// update the set of lights and repeat
Lights Out !
// draw the current set of lights
0
“on” lights
should be 4x4
blocks of stars
|
|
|
|
2
1
3
4
|****|****|****|
|****|****|****|
|****|****|****|
|****|****|****|
0
“off” lights should be
4x4 blocks of spaces
1
2
3
print light numbers close
to the center of each light
lights should be
separated with
vertical bars
5
|****|
|****|
|****|
|****|
4
5
6
7
may display all light
numbers up to 15
Lights Out !
// allow the user to select a light
//
only allow valid lights !