Lecture 6: Controlling the flow; toString
toString
For classes that we write, the default toString
method returns the memory location of the object. If we want something more useful, we can override the method.
Use this tutorial if you need another reference.
Loops
for
while
do while
: see this tutorial
Branches
if
else if
else
switch
: see this tutorial
Files used in class
See previous lecture for a toString
example. We will also use the Project 1 starter code to look at examples of controlling the flow.
Additional exercises
- R-1.5 from book: Write a short Java method that takes an integer
n
and returns the sum of all positive integers less than or equal ton
. - R-1.8 from book: Write a short Java method that counts the number of vowels in a given character string.
- Write a short Java method that takes a
char
grade and returns it as adouble
GPA score. You can use the following conversions: A (4.0), A- (3.7), B+ (3.3), B (3.0), B- (2.7), C+ (2.3), C (2.0), C- (1.7), D+ (1.3), D (1.0) and F (0.0). Write this method both using a series ofelse if
statements and using aswitch
statement.