Professional Documents
Culture Documents
Chapter 5
Control Structures: Part II
•
Java I--Copyright © 2000 Tom Hunter
Counter-Controlled Repetition
• The for Loop
• A common structure called a for loop is specially
designed to manage counter-controlled looping.
TRUE { body }
3. counter <= 10
?
FALSE counter++
4.
for(for(
int int
x = x1;= x1;;
< 10;
x++ x++
) )
int x = 1;
for( intx x< =10;
for(; 1; x++
x < )10; x++ )
for(
for(int
intx x= =1;1;x x< <10;
10;)
x++ )
{
other stuff
x++;
}
• You can omit the increment of
the variable if you are doing so
within the body of the loop.
Java I--Copyright © 2000 Tom Hunter
// Calculate Compound Interest
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import javax.swing.JTextArea;
} // end of for
System.exit( 0 );
} // end of main()
} // end of class Interest
Java I--Copyright © 2000 Tom Hunter
// Calculate Compound Interest
import javax.swing.JOptionPane;
Since Java has no exponentiation operator, we
import java.text.DecimalFormat;
calling on the Math library’s method (pow for
import javax.swing.JTextArea;
System.exit( 0 );
} // end of main()
} // end of class Interest
Java I--Copyright © 2000 Tom Hunter
// Calculate Compound Interest
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import javax.swing.JTextArea;
System.exit( 0 );
} // end of main()
} // end of class Interest
Java I--Copyright © 2000 Tom Hunter
// Calculate Compound Interest
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import javax.swing.JTextArea;
System.exit( 0 );
} // end of main()
} // end of class Interest
Java I--Copyright © 2000 Tom Hunter
Counter-Controlled Repetition
byte
short
int
char
w
Java I--Copyright © 2000 Tom Hunter
Multiple-Selection Structure
• The default: is optional.
• If you omit the default choice, then it is possible
for none of your choices to find a match and that
nothing will be executed.
w
Java I--Copyright © 2000 Tom Hunter
Multiple-Selection Structure
• Question: if only integer values can appear in the
switch( x ) statement, then how is it possible for
a char to be the expression?
while
do/while
for
switch
JTextArea( )
JScrollPane( )
JOptionPane( )
System.exit( 0 );
}
}
System.exit( 0 );
}
}
System.exit( 0 );
}
}
System.exit( 0 );
}
}
|| Logical OR
! Logical NOT
&&
• Again, this works just like the Logical OR, but you
are guaranteed that both sides of the expression will
always be executed.
• If either half is true, the entire ‘if’ is true.
Java I--Copyright © 2000 Tom Hunter
Logical Operators
• Logical exclusive Boolean OR.
^ ( shift 6 )