Transcript PowerPoint

Last Time
• Built “HelloWorld.java” in BlueJ (and Eclipse).
• Looked at Java keywords.
• Primitive types.
• Expressions: Variables, operators, literal values,
operator precedence.
Spring 2006
CISC101 - Prof. McLeod
1
Today
• Lab 1 and Assignment 1 are posted.
• A few more things to do with expressions:
–
–
–
–
Mixed type expressions
Casting – automatic (implicit) and explicit
Unary operators
Other assignment operators
• Screen Input/Output.
• Variable Scope
• Conditional (or “if” statements) – if we have time…
Spring 2006
CISC101 - Prof. McLeod
2
Mixed Type Expressions
• So far, we have been careful to have expressions
where all the types match.
• For example:
double rectArea = 4.1 * 5.2;
• rectArea contains 21.32
• Operators will only work when the values on both
sides of the operator are of the same type.
Spring 2006
CISC101 - Prof. McLeod
3
Mixed Type Expressions, Cont.
• Suppose the expression is:
double rectArea = 4 * 5.2;
• 4 is an int literal and 5.2 is a double literal.
• What do you think will happen?
• 4 is changed - “cast” - to be a double literal and
the evaluation proceeds. This is called “implicit”
casting, and it happens automatically.
Spring 2006
CISC101 - Prof. McLeod
4
Mixed Type Expressions, Cont.
• What will happen with:
double rectArea = 4 * 5;
• Both 4 and 5 are int literals.
• The * operation results in 20
• The int value 20 is cast to 20.0 and stored in
rectArea.
Spring 2006
CISC101 - Prof. McLeod
5
Mixed Type Expressions, Cont.
• So mixing int literals in expressions with
double’s is not a problem, as long as the result is
being saved in a double.
• int’s will be automatically cast to double’s (an
“implicit cast”), this is also called a “widening”
cast.
• What about:
int area = 4 * 5.2;
• 4 * 5.2 will evaluate to a double.
• Java will not compile this statement. Why not?
Spring 2006
CISC101 - Prof. McLeod
6
Mixed Type Expressions, Cont.
• Java will refuse to try and store the double
(10.4) in a variable of type int.
• Information would be lost.
• To do this, the code will have to tell Java that it is
OK to lose this information - this is called a
“narrowing” cast.
• Your code has to carry out a “narrowing” cast
explicitly, it will not be done automatically:
int area = (int)(4 * 5.2);
Spring 2006
CISC101 - Prof. McLeod
7
Casting
• The code: “(int)” is called a casting operator.
• Whatever follows the (int) will be cast to an
int value.
• Note that casting truncates, it does not round a
value. So, (int)10.9 is 10, not 11.
• Casting takes precedence over the arithmetic
operators.
• (The “unary” operators take precedence over
casting - but we have not discussed unary
operators, yet.)
Spring 2006
CISC101 - Prof. McLeod
8
Casting - Cont.
• “Implicit” casting is automatic, and will always go
in the direction:
byte > short > int > long > float > double
• Anytime you want to cast in the opposite direction,
you must use an “explicit” cast, using the
appropriate casting operator.
Spring 2006
CISC101 - Prof. McLeod
9
Aside - Integer Arithmetic
• Integer arithmetic gets interesting for division.
• What is the value in aVal for:
int aVal = 5 / 2;
•2
• Not 2.5, which would be a double!
• 5 / 2 yields an int, not a double since both 5
and 2 are int literals.
Spring 2006
CISC101 - Prof. McLeod
10
Integer Arithmetic, Cont.
• What is the value in aVal for:
int aVal = 20 / 3;
•6
• Not 7!
• Truncates, not rounds!
Spring 2006
CISC101 - Prof. McLeod
11
Integer Arithmetic, Cont.
• Similarly, what is:
int aVal = 1 / 5;
aVal is 0
• How about:
double aNum = 7 / 2;
Spring 2006
aNum is 3.0
CISC101 - Prof. McLeod
12
Unary Operators
• Binary operators required values on both sides of
the operator: * / - + % < > <= >= == !=
&& || =
• Unary operators operate on just one value, or
variable:
–
–
–
–
(casting)
- (negation)
++ -- (increment and decrement)
! (logical “NOT”)
Spring 2006
CISC101 - Prof. McLeod
13
Unary Arithmetic Operators
• Unary operators include “-”, where “-aNum” negates the
value produced by aNum, for example.
• They also include the increment (++) and decrement (--)
operators which increase or decrease an integer value by
1.
• Preincrement and predecrement operators appear
before a variable. They increment or decrement the value
of the variable before it is used in the expression.
• Example:
int i = 4, j = 2, k;
k = ++i - j;
// i = 5, j = 2, k = 3
Spring 2006
CISC101 - Prof. McLeod
14
Unary Arithmetic Operators - Cont.
• Postincrement and postdecrement operators
appear after a variable. They increment or
decrement the value of the variable after it is used
in the expression.
• Example:
int i = 4, j = 2, k;
k = i++ - j;
// i = 5, j = 2, k = 2
• Keep expressions involving increment and
decrement operators simple!
Spring 2006
CISC101 - Prof. McLeod
15
Unary Logical Operator
• The one “unary” logical operator is “!”.
• Called the “Not” operator.
• It reverses the logical value of a boolean.
• For example:
!(5 > 3) evaluates to false
Spring 2006
CISC101 - Prof. McLeod
16
The Other Assignment Operators
Syntax: variableName = expression;
=
set equal to (we’ve seen this one!)
*=
/=
-=
+=
multiply and set equal to
divide and set equal to
subtract and set equal to
add and set equal to
Spring 2006
CISC101 - Prof. McLeod
17
Assignment Operators - Cont.
• For example,
variableName += expression;
is equivalent to
variableName = variableName +
expression;
Spring 2006
CISC101 - Prof. McLeod
18
Screen I/O
• Your program would not be much use if it could
not communicate with the user!
• Screen input is your program obtaining
information - “values” - from the user.
• Screen output is your program sending
information to the screen for the user to read.
• Screen input in Java is not as simple as screen
output.
Spring 2006
CISC101 - Prof. McLeod
19
Screen Output
• Three methods in the System.out class for
Console window output:
– println()
– print()
– printf()
Spring 2006
(only in Java 5.0)
CISC101 - Prof. McLeod
20
Screen Output – Cont.
• (Also called “Text Window”…)
• Easy:
System.out.print( Stuff_to_Print );
System.out.println( Stuff_to_Print );
• “Stuff_to_Print” can be anything - not just a
String - these two methods are heavily
overloaded.
Spring 2006
CISC101 - Prof. McLeod
21
Screen Output - Cont.
• Note that:
System.out.print(“\n”);
is the same as:
System.out.println();
• So, println() appends a carriage
return/linefeed character sequence to the end of
the output, where print() does not.
Spring 2006
CISC101 - Prof. McLeod
22
Screen Output - Cont.
• “Escape sequences” can be used to control the
appearance of the output:
\”
\’
\\
\n
\r
\t
a double quote
a single quote
a backslash
a linefeed
a carriage return
a tab character
• These can be embedded anywhere in a String.
Spring 2006
CISC101 - Prof. McLeod
23
Screen Output - Cont.
• For example the following code:
System.out.println("\"Tabbed\" output:\t1\t2\t3\t4");
Prints the following to the screen:
"Tabbed" output:
Spring 2006
1
2
CISC101 - Prof. McLeod
3
4
24
printf Method
• Which statement provides the most sensible
output:?
double aNum = 17.0 / 3.0;
System.out.println("Using println: " + aNum);
System.out.printf("Using printf: %5.2f", aNum);
Using println: 5.666666666666667
Using printf: 5.67
Spring 2006
CISC101 - Prof. McLeod
25
printf Method, Cont.
• For more information follow the link: “Format
String Syntax” in the API listing for the printf
method.
• Basically use %width.decimalsf for float
and double numbers, and %d for int’s.
• You can have multiple numbers listed by using
multiple format placeholders.
Spring 2006
CISC101 - Prof. McLeod
26
Aside - Methods and Classes
• I’ve been talking about “methods” and “classes”
without really explaining them.
• For example, printf() is a method in the
System.out class.
• Methods cannot exist on their own - they must
“belong” to a class.
• In order for Java to find the method, you must tell
Java the name of the class that “owns” the
method.
Spring 2006
CISC101 - Prof. McLeod
27
Aside - Methods and Classes - Cont.
• Telling the Java compiler who owns the method is
done by using the “dot operator” - a fancy name
for a period.
• The period is used to separate the class name
from the method name:
• For example: System.out.println()
Class name
Spring 2006
Method name
CISC101 - Prof. McLeod
28
Aside - Methods and Classes - Cont.
• (If you are calling a method that exists within the
same class as your main method, you do not
need a class name or a period. We will see more
about this later!)
Spring 2006
CISC101 - Prof. McLeod
29
Console Input in Java 5.0
• Use the “Scanner” class. It must be imported
using:
import java.util.Scanner;
• In your program:
Scanner console = new Scanner(System.in);
Spring 2006
CISC101 - Prof. McLeod
30
Console Input in Java 5.0, Cont.
• Then, you can use the Object “console”, as
many times as you want calling the appropriate
method for whatever primitive type or String you
want to get from the user.
• For example:
System.out.print("Please enter a number: ");
double aNum = console.nextDouble();
Spring 2006
CISC101 - Prof. McLeod
31
Exercise
1. Write a program that accepts a double value from the
user and then displays the volume of a cube with
sides of the length provided.
• Hints:
– above public class: import java.util.Scanner;
– inside main:
• Scanner console = new Scanner(System.in);
• prompt the user
• Accept the input using console.nextDouble()
• Calculate and display the volume.
Spring 2006
CISC101 - Prof. McLeod
32
import java.util.Scanner;
public class VolumeCalculation {
public static void main (String[] args) {
double sideLength;
double volume;
Scanner console = new Scanner(System.in);
System.out.print("Enter side length: ");
sideLength = console.nextDouble();
volume = sideLength * sideLength * sideLength;
System.out.println("Volume is " + volume);
} // end main
} // end VolumeCalculation
Spring 2006
CISC101 - Prof. McLeod
33
Exercise, Cont.
2. Once your program works OK, try entering
something that is not a number, to see what
happens.
Spring 2006
CISC101 - Prof. McLeod
34
Other Scanner Class Input Methods
• Has an input method for each primitive type. (See
the API)
• Use .nextLine() to get the entire line as a
String.
Spring 2006
CISC101 - Prof. McLeod
35
Aside – “GUI”
• GUI (“Graphical User Interface”) is all about the
use of frames, laying out passive and interactive
components (text boxes, command buttons,
labels, etc.), and then attaching methods to
listener events, for user interaction.
• This might be fun?… But, we will not get
sidetracked in this course into what really is
design and not so much programming.
• Besides, an application with a nice GUI interface
can still be a lousy program if the underlying code
does not work well!
Spring 2006
CISC101 - Prof. McLeod
36
Aside, GUI – Cont.
• For screen output, you can use the JOptionPane
class, and invoke the showMessageDialog()
method.
JOptionPane.showMessageDialog(null, “Volume
is " + volume);
• The JOptionPane class is part of the javax.swing
package, so you must have the following line at
the top of your program:
import javax.swing.JOptionPane;
Spring 2006
CISC101 - Prof. McLeod
37
Aside, GUI – Cont.
• Produces the cute little window:
Spring 2006
CISC101 - Prof. McLeod
38
GUI Input
• Use the showInputDialog() method from the
JOptionPane class:
String message;
message = JOptionPane.showInputDialog("Enter
side length:");
• OK, but we have a String and we want a
number…
Spring 2006
CISC101 - Prof. McLeod
39
GUI Input - Cont.
• Use Scanner class again:
Scanner getNumber = new Scanner(message);
sideLength = getNumber.nextDouble();
• If message does not contain a double number,
then an exception will be thrown.
Spring 2006
CISC101 - Prof. McLeod
40
GUI Input, Cont.
• So, to prevent crashing our program, we need to
catch an Exception, specifically a
“java.lang.NumberFormatException”.
• Once we catch it we need to do something
sensible to prevent the problem from crashing the
rest of our program. Our program would be more
robust!
• (Except we do not know how to catch exceptions
– yet…)
Spring 2006
CISC101 - Prof. McLeod
41
import java.util.Scanner;
import javax.swing.JOptionPane;
public class VolumeCalculationGUI {
public static void main (String[] args) {
double sideLength;
double volume;
String message;
message = JOptionPane.showInputDialog("Enter side length:");
Scanner getNumber = new Scanner(message);
sideLength = getNumber.nextDouble();
volume = sideLength * sideLength * sideLength;
JOptionPane.showMessageDialog(null, "Volume is " + volume);
} // end main
Spring 2006
} //
end VolumeCalculationGUI CISC101 - Prof. McLeod
42
Screen I/O, Summary
• For this course, you can user either console I/O or
JOptionPane I/O.
• Don’t use both in a single program!
• For now, assume that the user will supply the type
requested. Later you can make more robust
programs using exceptions.
• We will not spend the time require to learn how to
write full GUI programs in this course.
Spring 2006
CISC101 - Prof. McLeod
43
Variable Scope
• Variables are only “known” within the block in
which they are declared.
• If a block is inside another block, then a variable
declared in the outer block is known to all blocks
inside the outer one.
• “known” means that outside the block in which
they are declared, it is as if the variable does not
exist.
• For example:
Spring 2006
CISC101 - Prof. McLeod
44
public class ScopeTest {
public static void main (String[] args) {
// block 1
{
int aVal = 6;
}
// block 2
{
aVal = 10;
}
} // end main method
} // end ScopeTest
Spring 2006
CISC101 - Prof. McLeod
45
Variable Scope – Cont.
• Note that both block 1 and block 2 are contained
within the main method’s block, which itself is
contained within the block for the class definition.
• This program will not even compile.
• The “aVal = 10;” line will be highlighted and the
following error message will be shown:
Error: No entity named “aVal” was found in this
environment.
• Next example:
Spring 2006
CISC101 - Prof. McLeod
46
public class ScopeTest {
public static void main (String[] args) {
int aVal;
// block
{
aVal
}
// block
{
aVal
}
1
= 6;
2
= 10;
} // end main method
} // end ScopeTest
Spring 2006
CISC101 - Prof. McLeod
47
Variable Scope – Cont.
• This program compiles and runs fine.
• aVal is declared in the same block that contains
block 1 and block 2, so aVal is known inside both
blocks.
• One more example:
Spring 2006
CISC101 - Prof. McLeod
48
public class ScopeTest {
public static void main (String[] args) {
// block 1
{
int aVal = 6;
}
// block 2
{
int aVal = 10;
}
} // end main method
} // end ScopeTest
Spring 2006
CISC101 - Prof. McLeod
49
Variable Scope – Cont.
• This program compiles and runs fine, but is
considered Very Bad Form!
• You should never re-declare a variable within a
method!
• These two variables are completely separate as
far as the compiler knows, but any person reading
your code will be confused!
Spring 2006
CISC101 - Prof. McLeod
50
So Far…
• So far, all our programs have been linear:
etc.
Spring 2006
CISC101 - Prof. McLeod
51
Branching Algorithms
• If a program could test a condition, then it would
have a choice as to its path of execution:
if true
if false
etc.
Spring 2006
CISC101 - Prof. McLeod
52
Conditionals or “Selection Statements”
• Java has “if”, “if-else” and “switch”
statements.
• Simple if statement syntax:
if (boolean_expression)
statement_when_true;
• Example:
if (capacitance < 0)
System.out.println(“Illegal capacitance”);
Spring 2006
CISC101 - Prof. McLeod
53
if Statement
• You might want to carry out more than one
statement when a condition is true.
• For example if the capacitance is negative (an
“illegal” value) then re-prompt the user for positive
value:
if (capacitance < 0) {
System.out.print(“Illegal value, please re-enter: ”);
// code to obtain another value from the user
} // end if
• So, you can enclose a block of statements within
“{}”.
Spring 2006
CISC101 - Prof. McLeod
54
if-else Statement
• Syntax of “if-else” statement:
if (boolean_expression)
statement_when_true;
else
statement_when_false;
• Example:
if (stress > maxStress / 1.5)
result = “failure”;
else
result = “pass”;
Spring 2006
CISC101 - Prof. McLeod
55
if-else Statement, Cont.
• With statement blocks:
if (boolean_expression) {
block_of_code_when_true
}
else {
block_of_code_when_false
}
Spring 2006
CISC101 - Prof. McLeod
56
if Statement, Cont.
• You will often have to nest if statements:
etc.
Spring 2006
CISC101 - Prof. McLeod
57
Nested if Statements
• For example, if you have three numbers, a, b, & c
and you want to print them to the screen in order:
T
T
b<c
T
abc
acb
Spring 2006
F
a<b
T
b<c
a<c
F
F
F
a<c
cab
T
bac
CISC101 - Prof. McLeod
F
cba
bca
58
Nested if Statements - Cont.
• Nested if statements can be tricky to code make sure you create test cases that will test
every possible path through all the conditionals.
Spring 2006
CISC101 - Prof. McLeod
59
“Chained” if Statements
• Syntax:
if (condition1) { block1 }
else if (condition2) { block2 }
else if (condition3) { block3 }
else if (condition4) { block4 }
…
else { blockn }
• Each condition is tested in turn, until one is
evaluated to true. If none of them are true then
the else block is executed.
Spring 2006
CISC101 - Prof. McLeod
60
switch Statement
• Syntax:
switch (expression) {
case val1:
// statements if expression produces val1
break;
case val2:
// statements if expression produces val2
break;
case val3:
…
default:
// statements if none of the above is true
break;
} // end switch
Spring 2006
CISC101 - Prof. McLeod
61
switch Statement - Cont.
• The code to be run depends on which val# value
matches expression.
• If none match, the statements after the default:
clause are run.
• The expression and val# values (or “Case
Labels”) must all be of the same integer type.
• The break; statements make sure that following
cases are not executed after a match has been
made.
• It is possible to do multiple cases on one line, but
it is clumsy:
Spring 2006
CISC101 - Prof. McLeod
62
switch Statement - Cont.
switch (expression) {
case val1: case val2: case val3:
// statements if expression is val1, val2 or
val3
break;
case val4: case val5:
// statements if expression is val4 or val5
break;
case val6:
…
default:
// statements if none of the above is true
break;
} // end switch
Spring 2006
CISC101 - Prof. McLeod
63
switch Statement - Cont.
• Not too useful a construct.
• Menu coding, for example, is a possible use:
– Provide a number of options to the user, like “(A)dd,
(E)dit or (D)elete”.
– The user presses a, e, d, A, E, D, or some other key.
– In a switch statement, you would have:
Spring 2006
CISC101 - Prof. McLeod
64
switch Statement - Cont.
switch (userResponse) { // userResponse is a char
case ‘a’: case ‘A’:
// Add operation code
break;
case ‘e’: case ‘E’:
// Edit operation code
break;
case ‘d’: case ‘D’:
// Delete operation code
break;
default:
// Tell user wrong key pressed
break;
} // end switch
Spring 2006
CISC101 - Prof. McLeod
65
Exercise
1. Obtain an outdoor temperature (in degrees Centigrade)
from the user.
2. If the temperature is less than -40, or greater than +40
tell him that the temperature is not legal and exit the
program.
3. If the temperature is >= -40, but less than 0, display “It is
cold! Wear a parka.”.
4. If the temperature is >= 0, but less than 15, display “It is
cool. Wear a jacket.”.
5. If the temperature is >= 15 and less than 25, display “It is
nice! Wear shorts.”.
6. If the temperatuer is >=25 and less than 40, display “It is
hot! Seek the beach!”.
Spring 2006
CISC101 - Prof. McLeod
66
Repetition or Using “Loops”
• We will discuss:
– while
– do/while
– for
– The “for each” loop in Java 5.0
– Use of “break” and “continue”
Spring 2006
CISC101 - Prof. McLeod
67
Repetition or “Loops”
• Suppose we combine a boolean test with some kind of
structure that allows us to branch back up to an earlier
piece of code:
if true
if false
etc.
Spring 2006
CISC101 - Prof. McLeod
68
Repetition - Cont.
• The boolean test determines when to stop the
repetition - as long as the condition is true, the
loop keeps going.
• Something inside the looping part must affect
what is tested in the condition - right? What if it
did not - what would happen?
Spring 2006
CISC101 - Prof. McLeod
69
Repetition - Cont.
• A simple example - suppose we wanted a loop to
execute only 20 times:
i=1
if true
if false
i < 21
i = i+1
etc.
Spring 2006
CISC101 - Prof. McLeod
70
Repetition - Cont.
• The number of repetitions is controlled by
changing the limit value for the loop counter - “i”
in the example on the previous slide.
• That example had i increasing by one each time.
The loop counter was being incremented by one.
• It could have been incremented by some other
value, 2, 3, or whatever.
• You could use something like “i = i * 2” to
increment the counter.
• If the counter is decreased in value each time, it is
being “decremented”.
Spring 2006
CISC101 - Prof. McLeod
71
Repetition - Cont.
• Suppose, in the previous example, i was
decremented by one instead. What would
happen?
i=1
if true
if false
i < 21
i=i-1
etc.
Spring 2006
CISC101 - Prof. McLeod
72
Repetition - Cont.
• The dreaded “infinite loop”!
• The java compiler will not prevent you from coding
a loop like the one shown - it will compile, and it
will run!
• And run, and run, and run, and run, and run, and run, and run,
and run, and run, and
run…
• As a programmer, you must be “on guard” for
such logic errors in your code.
Spring 2006
CISC101 - Prof. McLeod
73
Aside - Increment and Decrement
Operators
• In loops, expressions like:
j = j + 1; and
k = k - 1;
are used so often, it is typical to see the
postincrement operator:
j++; is the same as j = j + 1;
k--; is the same as k = k - 1;
• You can use either notation.
Spring 2006
CISC101 - Prof. McLeod
74
“while” loop
• A java while loop can be used to code the structure
shown in the flowchart above (the “increment” one on slide
27):
int i = 1;
while (i < 21) {
// other statements
i = i + 1; // or you could use i++:
} // end while
• The “{ }” brackets enclose the statements that are
repeated.
• (A single statement to be repeated in the loop does not
require the “{}”.)
Spring 2006
CISC101 - Prof. McLeod
75
“while” loop - Cont.
• Note that java (thank goodness!!!) does not have
anything equivalent to a “goto” statement.
• (And if it did, I would not tell you about it,
anyways!!)
• So, you cannot construct a loop with an “if”
statement and a goto.
• An “if” statement cannot give you repetition, it
only allows you to decide on a single pass
through a branch of code.
Spring 2006
CISC101 - Prof. McLeod
76
“while” loop - Cont.
• while loop syntax:
while ( boolean_expression ) {
block_of_code
}
• As long as boolean_expression evaluates to true the
statements in the block_of_code continue to execute.
• By mistake, you might write the following - what would
happen?
while ( boolean_expression ); {
block_of_code
}
Spring 2006
CISC101 - Prof. McLeod
77
“while” loop - Cont.
• The boolean expression tested in a while loop could be
false to start with:
int i = 40;
while (i < 21) {
// other statements
i = i + 1;
}
• In this case, the loop would not execute at all.
• Use a “do/while” loop if you need a loop that will always
run at least once:
Spring 2006
CISC101 - Prof. McLeod
78
“do/while” loop
• Syntax:
do {
block_of_code
} while ( boolean_expression );
• Note the “;” at the end of the while statement.
• Since the conditional test is at the end of the loop,
it will always execute the loop at least once.
Spring 2006
CISC101 - Prof. McLeod
79
“do/while” loop - Cont.
• For example, suppose we must obtain a value between 1
and 100, inclusive, from the user:
int aVal = 0; // The compiler will force us to
// initialize aVal
do {
System.out.print(“Enter value between 1 and 100:”);
// code to obtain a value from the user
} while (aVal < 1 || aVal > 100);
• As long as the user does not do what he is told, the loop
will continue to re-prompt him for the correct value.
Spring 2006
CISC101 - Prof. McLeod
80
“for” loop
• The kind of while loop shown above:
int i = 1;
while (i < 21) {
// other statements
i = i + 1;
}
is used so often, that Java has provided another looping
structure that does all that is shown above, but needs
only one line:
for (int i = 1; i < 21; i = i + 1) {
// other statements
}
Spring 2006
CISC101 - Prof. McLeod
81
“for” loop - Cont.
• Or, as written with an increment operator:
for (int i = 1; i < 21; i++) {
// other statements
}
• Syntax:
for (initialization; boolean_expression; update) {
block_of_code
}
• for loops are used when you know, in advance, the
number of repetitions desired.
Spring 2006
CISC101 - Prof. McLeod
82
“for” loop - Cont.
• You don’t have to declare the counter inside the
for loop, if you have declared it earlier in your
program.
• But if you do declare it in the “for” statement then
the scope of that variable will only be inside the
loop block.
Spring 2006
CISC101 - Prof. McLeod
83
“for each” Loop in Java 5.0
• Often, you will want to “visit” every element in a
collection, not just a part.
• Syntax of the “for each” loop:
for (type_variable : collection) {
// statements
}
• These loops are only used with collections.
Spring 2006
CISC101 - Prof. McLeod
84
“for each” Loop in Java 5.0, Cont.
• (We don’t know what arrays are yet, but just for
now:)
• For example, suppose we have an array called
“data”, containing a collection of double type
numbers, and you want to add them all up:
double sum = 0;
for (double e : data) {
sum = sum + e;
// or sum += e;
}
Spring 2006
CISC101 - Prof. McLeod
85
“for each” Loop in Java 5.0, Cont.
• Equivalent normal “for” loop:
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
//or sum += data[i];
}
• The “for each” loop is a bit easier with arrays, but
is even better suited for other kinds of collections.
Spring 2006
CISC101 - Prof. McLeod
86
Loops - Misc.
• Don’t declare variables inside loops, as the repeated
declaration process uses up time and memory
unnecessarily.
• Loops are often nested - to usually not more than three
levels. For example:
int i, j;
int sum = 0;
for (i = 1; i <= 100; i++)
for (j = 1; j <= 10; j++)
sum++;
• sum would be 1000.
Spring 2006
CISC101 - Prof. McLeod
87
Loops - Misc. - Cont.
• There is no limit in Java to how many levels you
can nest loops.
• It is customary, but not necessary, to use the
variables i, j, k as loop counters.
• Loops really demonstrate the strength of
computers as they allow the machine to complete
mind-numbingly boring tasks with perfect
accuracy!
• Loops will always be used with any file I/O and
array operations.
Spring 2006
CISC101 - Prof. McLeod
88
Other Java Keywords Used With Loops
• break and continue
• The continue statement interrupts the execution
of a loop, and returns control to the top of the
loop.
• The break statement interrupts the execution of
a loop, and transfers control to the first statement
after the loop.
Spring 2006
CISC101 - Prof. McLeod
89
Use of “continue”
• For example,
Return to top of
loop when executed
for ( i = 1; i <= 5; i++) {
if ( i == 3 ) continue;
System.out.println("i = " + i);
}
System.out.println("End of loop!");
• Would print:
Spring 2006
i =
i =
i =
i =
End
1
2
4
5
of loop!
CISC101 - Prof. McLeod
90
Use of “break”
• For example,
Transfer to the first
statement after end of
loop when executed
for ( i = 1; i <= 5; i++) {
if ( i == 3 ) break;
System.out.println("i = " + i);
}
System.out.println("End of loop!");
• Would print:
16 September 2002
i = 1
i = 2
End of loop!
Fall 2002 CISC121 - Prof. McLeod
91
Use of “break” & “continue”
• Only use these keywords when it makes your
code easier to read.
• Avoid the use of more than one break or continue
inside a loop.
• If you use a condition to issue a break statement,
then why can’t you put that condition in the loop
test?
• Overuse of break statements can lead to
“spaghetti” code - just like the use of “goto”
statements!
Spring 2006
CISC101 - Prof. McLeod
92