Professional Documents
Culture Documents
Selection
Statements
Using if and if...else
Nested if Statements
Using switch Statements
Conditional Operator
Repetition
Statements
Selection Statements
if Statements
switch Statements
Conditional Operators
if Statements
if (booleanExpression) {
statement(s);
}
Example:
if ((i > 0) && (i < 10)) {
System.out.println("i is an " +
"integer between 0 and 10");
}
Caution
Addingasemicolonattheendofanifclauseis
acommonmistake.
if (radius >= 0);
Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
Thismistakeishardtofind,becauseitisnot
acompilationerrororaruntimeerror,itisa
logicerror.
Thiserroroftenoccurswhenyouusethenext
lineblockstyle.
if...else Example
if (radius >= 0) {
area = radius*radius*PI;
System.out.println("The area for the
+ circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
Note
Theelseclausematchesthemostrecentifclause
inthesameblock.Forexample,thefollowing
statement
int i = 1; int j = 2; int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
isequivalentto
int i = 1; int
j = 2; int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
Note, cont.
Nothingisprintedfromthepreceding
statement.Toforcetheelseclauseto
matchthefirstifclause,youmustadda
pairofbraces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
ThisstatementprintsB.
Nested if Statements
Example 3.1 Using Nested if Statements
This program reads in number of years and
loan amount and computes the monthly
payment and total payment. The interest
rate is determined by number of years.
TestIfElse
Run
switch Statements
switch (year) {
case 7: annualInterestRate = 7.25;
break;
case 15: annualInterestRate = 8.50;
break;
case 30: annualInterestRate = 9.0;
break;
default: System.out.println(
"Wrong number of years, enter 7, 15, or 30");
}
Theswitchexpressionmustyieldavalueofchar,
byte,short,orinttypeandmustalwaysbe
enclosedinparentheses.
Thevalue1,...,andvalueNmusthavethesame
datatypeasthevalueoftheswitchexpression.
Theresultingstatementsinthecasestatement
areexecutedwhenthevalueinthecasestatement
matchesthevalueoftheswitchexpression.(The
casestatementsareexecutedinsequential
order.)
Thekeywordbreakisoptional,butitshouldbe
usedattheendofeachcaseinorderto
terminatetheremainderoftheswitchstatement.
Ifthebreakstatementisnotpresent,thenext
casestatementwillbeexecuted.
Theorderofthecases(includingthe
defaultcase)doesnotmatter.However,it
isagoodprogrammingstyletofollowthe
logicalsequenceofthecasesandplace
thedefaultcaseattheend.
Caution
Donotforgettouseabreakstatementwhen
oneisneeded.Forexample,thefollowingcode
alwaysdisplaysWrongnumberofyears
regardlessofwhatnumOfYearsis.Supposethe
numOfYearsis15.Thestatement
annualInterestRate=8.50isexecuted,then
thestatementannualInterestRate=9.0,and
finallythestatement
System.out.println("Wrongnumberofyears").
switch (numOfYears) {
case 7: annualInterestRate = 7.25;
case 15: annualInterestRate = 8.50;
case 30: annualInterestRate = 9.0;
default: System.out.println("Wrong number of years");
}
Conditional Operator
if (x > 0) y = 1
else y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
Ternary operator
Binary operator
Unary operator
Conditional Operator
if (num % 2 == 0)
System.out.println(num + is even);
else
System.out.println(num + is odd);
System.out.println(
(num % 2 == 0)? num + is even :
num + is odd);
Repetitions
while Loops
do-while Loops
for Loops
break and continue
int i = 0;
while (i < 100) {
System.out.println(
"Welcome to Java!");
i++;
}
(i < 100)
false
true
System.out.println("Welcoem to Java!");
i++;
Next
Statement
TestWhile
Run
Caution
Dontusefloatingpointvaluesforequality
checkinginaloopcontrol.Sincefloating
pointvaluesareapproximations,usingthem
couldresultinimprecisecountervaluesand
inaccurateresults.Thisexampleusesint
valuefordata.Ifafloatingpointtypevalue
isusedfordata,(data!=0)maybetrueeven
thoughdatais0.
// data should be zero
double data = Math.pow(Math.sqrt(2), 2) - 2;
if (data == 0)
System.out.println("data is zero");
else
System.out.println("data is not zero");
do-while Loop
Statement(s)
do {
// Loop body;
} while (continue-condition);
true
Continue
condition?
false
Next
Statement
for Loops
for (initial-action; loop-continuation-condition;
action-after-each-iteration) {
//loop body;
}
int i = 0;
while (i < 100) {
System.out.println("Welcome to Java! + i);
i++;
}
Example:
int i;
for (i = 0; i<100; i++) {
System.out.println("Welcome to Java! + i);
}
i=0
i++
i<100?
false
true
System.out.println(
Welcom to Java!);
Next
Statement
Run
Run
Caution
Addingasemicolonattheendofthe
forclausebeforetheloopbodyisa
commonmistake,asshownbelow:
Wrong
Caution, cont.
Similarly,thefollowingloopisalso
wrong:
Wrong
int i=0;
while (i<10);
{
System.out.println("i is " + i);
i++;
}
Inthecaseofthedoloop,the
followingsemicolonisneededtoendthe
loop.
int i=0;
do {
System.out.println("i
is " + i);
Correct
i++;
} while (i<10);
Run
Run
Example 3.7
Finding the Sales Amount
Youhavejuststartedasalesjobina
departmentstore.Yourpayconsistsofabase
salaryandacommission.Thebasesalaryis
$5,000.Theschemeshownbelowisusedto
determinethecommissionrate.
SalesAmount
CommissionRate
$1$5,000
8percent
$5,001$10,000 10percent
$10,001andabove
12percent
Yourgoalistoearn$30,000inayear.Writea
programthatwillfindouttheminimumamount
ofsalesyouhavetogenerateinordertomake
FindSalesAmount
Run
$30,000.
Example 3.8
Displaying a Pyramid of Numbers
Inthisexample,youwillusenestedloopsto
printthefollowingoutput:
1
212
32123
4321234
543212345
Yourprogramprintsfivelines.Eachline
consistsofthreeparts.Thefirstpart
comprisesthespacesbeforethenumbers;the
secondpart,theleadingnumbers,suchas321
PrintPyramid
Run
online3;andthelastpart,theending
numbers,suchas23online3.
Example 3.9
Displaying Prime Numbers
Thisexampledisplaysthefirst50prime
numbersinfivelines,eachofwhichcontains
10numbers.Anintegergreaterthan1isprime
ifitsonlypositivedivisoris1oritself.
Forexample,2,3,5,and7areprimenumbers,
but4,6,8,and9arenot.
Theproblemcanbebrokenintothefollowing
tasks:
Fornumber=2,3,4,5,6,...,testwhether
thenumberisprime.
Determinewhetheragivennumberisprime.
Counttheprimenumbers.
PrimeNumber
Run
Printeachprimenumber,andprint10numbers
perline.