Date post: | 03-Jan-2016 |
Category: |
Documents |
Upload: | alexandra-howard |
View: | 215 times |
Download: | 1 times |
This week in CS 5
• HW 9 (2 problems)
M/T sections
W/Th sections
due Sunday, 11/4 at midnight
due Monday, 11/5 at midnight
Recitation for HW9 -- Friday 11/2
A dizzying array of possibilities...
Reading: Week 9’s online notes
This week’s honorees are truly frightening...
John Conway
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;
return;}
PASSBY
VALUE
“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 from input for (int r=0 ; r<3 ; ++r) { for (int c=0 ; c<4 ; ++c) { bigarray[r][c] = H.in.nextDouble(); } }
Problem 1
1 Display prices2 Compute average of prices3 Compute variance of prices4 Display index and value of lowest price5 Display index and value of highest price6 Your TTS investment strategy
9 Quit
Which choice would you like?
Menu
An array of different methods...
Initial Input Get the number of stock prices from the user
Then, get each stock price from the user into the array.
Create an array of the appropriate number of elements.
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;}
Method notes
double averageArray(double[] arr)
double variance(double[] arr)
int indexOfSmallest(double[] arr)
int indexOfLargest(double[] arr)
Problem 2
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
A starting row of lights
2 is selected Each turn, a light is selected -- It and its neighbors switch states.
Goal: get all the lights off…
on on off off off on
Lights Out -- Printing
// draw the current set of lights
0 1 2 3 4 5
| |****|****|****| |****| | |****|****|****| |****| | |****|****|****| |****| | |****|****|****| |****|
0 1 2 3 4 5 6 7
lights should be separated with vertical bars
may display all light numbers up to 15
print light numbers close to the center of each light
“off” lights should be 4x4 blocks of spaces
“on” lights should be 4x4 blocks of stars
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();}
for (int i=len-1 ; i>=0 ; --i){ H.out.print( quip[i] + “ ” );}
Arrays in pictures
int len
String[] quip
quip[0]quip[1]
quip[2] quip[4]quip[3]
5
fall
leaves
after
leaves
fall
i is 4 i is 3 i is 2 i is 1 i is 0
fall leaves after leaves fall
public static int numSyllables(String w){ int numSyls = 0; int len = w.length();
if ( isVowel(w.charAt(0)) ) // an initial vowel ? ++numSyls;
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) // every word has at least 1 syllable numSyls = 1;
return numSyls;}
Syllable counting
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.)
A puzzle...
String s1 = H.in.nextWord();String s2 = H.in.nextWord();String s3 = H.in.nextWord();String s4 = H.in.nextWord();String s5 = H.in.nextWord();
H.out.print( s5 + “ ” );H.out.print( s4 + “ ” );H.out.print( s3 + “ ” );H.out.print( s2 + “ ” );H.out.print( s1 + “\n” );
Not a very flexible solution...
Arrays - lists of data items
String[] quip;
quip = new String[5];
for (int i=0 ; i<5 ; ++i){ quip[i] = H.in.nextWord();}
declares a String array named quip
declares five Strings named quip[0]…quip[4]
loop through the array
index
Arrays in code
H.out.println(“Type the number of words: ”);int len = H.in.nextInt();
String[] quip; // create an empty arrayquip = new String[len]; // create array elements
for (int i=0 ; i<len ; ++i){ quip[i] = H.in.nextWord(); // input each element}
// now print them out in reverse order…
Sentence palindromes
bores are people that say that people are bores
fall leaves after leaves fall
you can cage a swallow, can’t you, but you can’t swallow a cage, can you?
First Ladies rule the state and state the rule, “Ladies First!”
Strings
Be careful not to go out of bounds!
Element typesdouble, int, String,boolean, char, (any type) … char
The ith element
Example Declaration
Length
arr[i] s.charAt(i)
double[] arr;arr = new double[100];
String s;
java.lang.StringIndexOutOfBoundsException: -1
java.lang.ArrayIndexOutOfBoundsException: -1
arr.length s.length()
Warning
Range from 0 up to length-1
vsArrays
T. T. Securities
Input stock prices for a number of days in a row, and then analyze that data… .
1 Display prices2 Compute average of prices3 Compute standard deviation of prices4 Display index and value of lowest price5 Display index and value of highest price6 Your TTS investment strategy
9 Quit
Which choice would you like?
Menu:
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);}
public static double sumArray(double[] arr){ // see previous page … return sum;}
double[] stocks
90.0 10.0 60.0 42.0 75.0 70.0
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);}
public static double sumArray(double[] arr){ // see previous page … return sum;}
double[] stocks
90.0 10.0 60.0 42.0 75.0 70.0
double[] arr
2 references referring to the same list of data
T. T. Securities
Find the most profitable strategy for buying and selling the stock among the prices in the array...
Day 0 Price is 90.0Day 1 Price is 10.0Day 2 Price is 60.0Day 3 Price is 42.0Day 4 Price is 75.0Day 5 Price is 70.0
Lights Out !
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
A starting row of lights
2 is selected Each turn, a light is selected -- It and its neighbors switch states.
Goal: get all the lights off…
on on off off off on
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 1 2 3 4 5
| |****|****|****| |****| | |****|****|****| |****| | |****|****|****| |****| | |****|****|****| |****|
0 1 2 3 4 5 6 7
lights should be separated with vertical bars
may display all light numbers up to 15
print light numbers close to the center of each light
“off” lights should be 4x4 blocks of spaces
“on” lights should be 4x4 blocks of stars