home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
lect13a
(un)nested loops
-
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.)
(lect13a-soln.html)
-
Given an array of strings,
count how many times the letter 'A'
occurs in the entire array.
Hint:
We have already written
countOccurrences(String,char).
(lect13a-soln.html)
-
We will re-write the same method,
but use a “nested loop”.
Do you have a preference for one version or the other? Why?
Compiling and Running Java from the command line
Note:
If you are not using and IDE like Java,
we can still write, compile, and run Java programs:
-
To write your program, use any editor.
A class Foo
must be contained inside a file named Foo.java.
Microsoft Word will work; you should probably use a mono-width font
to help emphasize indentation/alignmnet
(e.g. Courier New or Lucida Sans Typewriter).
-
Running and compiling will be done by the command-line,
so the first step is to bring up a command shell.
In Windows, Start > Run and type cmd;
in Mac run the program Terminal
(found in /Applications/Utilities).
-
To compile your program from the command-shell:
javac Foo.java
If there are errors, the compiler will print them and stop.
If everything works fine, nothing apparent will happen
(although a file Foo.class has been created,
if you happen to look for it).
-
To run your program from the command-shell:
java Foo
This causes the Java runtime system to
find the class Foo
(in the file Foo.class),
and run its main method.
(Now you see why main must be public
and static.)
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs