home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
lect12c
arrays of strings
So far, we've been dealing with arrays of double.
However, we can have an array which hold any type of data1
With a neighbor, work through the methods we wrote previously,
but adapt them to Strings:
-
Given an array of Strings and a threshhold n,
count how many elements of the array have a length which is are at least n.
(You can compare this to countBigger
from last lecture.)
-
We will re-write this while-loop
using a for-loop.
You can use either loop to do the same thing,
but for-loops are particularly idiomatic
when you have a number as your index variable.
More generally, you might wonder:
“Why does Java provide a for-loop,
when a while-loop already does everything I need?”.
The reason is that the for-loop provides us with
a nice trait:
it puts all the index-variable manipulation on a single line,
and leaves all details of
updating the SoFar-variable (the accumulator)
to the body of the loop.
It is helpful to be able to think of those tasks separately,
and helpful to have a language feature which lets us
make our
thought-patterns manifest.
-
In-class exercise, for for:
Re-write
countOccurrences(String,char)
using for-loop.
-
Self-exercise:
Given an array of Strings,
find the maximum value
— either the longest String,
or the alphabetically last, whichever you prefer.
(The array's length is non-zero, as a pre-condition.)
(You can compare this to max
from last lecture.)
-
Self-exercise:
Given an array of Strings,
find the index of the maximum value.
(You can compare this to indexMax
from last lecture.)
(Finished here, Apr.17 (Fri))
-
Given an array of Strings,
does it contain a given target word?
This loop is a bit different — we can stop the loop
as soon as we find one occurrence!
(Imagine, passing in the text of a novel and searching for the
word “the” — we definitely don't want to continue
searching every word if we find the target right near the beginning.)
-
Given the array of Strings,
count how many times the letter 'A'
occurs in the entire array.
Hint:
We have already written
countOccurrences(String,char).
-
We will re-write the same method,
but use a “nested loop”.
Do you have a preference for one version or the other? Why?
1
Including: RoachPopulation[],
and even an array of arrays — double[][]!
↩
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs