Professional Documents
Culture Documents
TRUE/FALSE
1. You write pseudocode in everyday language, not the syntax used in a programming language.
3. When you create a block, you must place multiple statements within it.
4. When you use nested if statements, you must pay careful attention to placement of any else clauses.
5. In the switch structure, break is followed by one of the possible values for the test expression and
a colon.
7. When writing a statement with the two-line format, you must be sure to type a semicolon at the end of
the first line in order to ensure accurate results.
8. Although it is possible to block statements that depend on an if, you cannot likewise block statements
that depend on an else.
9. Although not required, it is common procedure to align the keyword if with the keyword else.
ANS: T PTS: 1 REF: 248
10. Range checking and the switch statement are tools programmers can use for effective decision
making.
MULTIPLE CHOICE
1. A ____ consists of written steps in diagram form, as a series of shapes connected by arrows.
a. pseudocode chart c. sequence structure
b. flowchart d. decision structure
ANS: B PTS: 1 REF: 242
2. A logical structure called a(n) ____ structure is when one step follows another unconditionally.
a. straight c. sequence
b. decision d. unconditional
ANS: C PTS: 1 REF: 242
3. The simplest statement you can use to make a decision is the ____ statement.
a. this c. true false
b. Boolean d. if
ANS: D PTS: 1 REF: 244
5. A(n) ____ statement is the decision structure you use when you need to take one or the other of two
possible courses of action.
a. Boolean c. single-alternative if
b. dual-alternative if d. if…else
ANS: B PTS: 1 REF: 247
6. When you execute an if…else statement, only one of the resulting actions takes place depending on
the evaluation of the ____ following the if.
a. Boolean expression c. else statement
b. keyword d. independent statement
ANS: A PTS: 1 REF: 247
7. When you place a block within an if statement, it is crucial to place the ____ correctly.
a. periods c. commas
b. angle brackets d. curly braces
ANS: D PTS: 1 REF: 251
8. Just as you can block statements that depend on an if, you can also block statements that depend on
a(n) ____.
a. Boolean expression c. constant
b. else d. operator
ANS: B PTS: 1 REF: 252
9. When you block statements, you must remember that any ____ you declare within a block is local to
that block.
a. method c. variable
b. expression d. decision
ANS: C PTS: 1 REF: 254
10. Statements in which an if structure is contained inside another if structure are commonly called
____ if statements.
a. nested c. blocked
b. logical d. inside
ANS: A PTS: 1 REF: 256
11. The compiler does not take indentation into account when compiling code, but consistent indentation
can help readers understand a program’s ____.
a. machine language c. decision
b. class d. logic
ANS: D PTS: 1 REF: 258
13. Failing to include a complete ____ on each side of an && operator in an if statement is a common
error in Java programming.
a. mathematical expression c. variable
b. Boolean expression d. operator
ANS: B PTS: 1 REF: 260
14. You can use the ____, which is written as ||, if you want some action to occur when at least one of
two conditions is true.
a. conditional OR operator c. range check
b. logical AND operator d. switch statement
ANS: A PTS: 1 REF: 261
15. A(n) ____ is a series of if statements that determine whether a value falls within a specified range.
a. scope check c. range test
b. if check d. range check
ANS: D PTS: 1 REF: 265
16. The ____ statement is useful when you need to test a single variable against a series of exact integer,
character, or string values.
a. switch c. else
b. if d. break
ANS: A PTS: 1 REF: 271
17. You can leave out the ____ statements in a switch structure.
a. break c. if
b. switch d. case
ANS: A PTS: 1 REF: 271
18. The ____ requires three expressions separated with a question mark and a colon.
a. flowchart c. sequence structure
b. conditional operator d. conditional statement
ANS: B PTS: 1 REF: 276
21. When working with logical operators, you can always use ____ to change precedence.
a. conditional operators c. parentheses
b. break statements d. semicolons
ANS: C PTS: 1 REF: 280
22. A ____ checks a value, and based on the result performs one of two actions.
a. short-circuit structure c. decision structure
b. sequence structure d. block structure
ANS: C PTS: 1 REF: 243
23.
Using the flowchart above, which decision statement will correctly check that hoursWorked is
greater than or equal to the FULL_WEEK constant?
24. if (quotaAmt > 100 || sales > 100 && productCode == "C")
bonusAmt = 50;
a. && c. ||
b. == d. =
ANS: A PTS: 1 REF: 279
25. When using equals and not equals for comparisons with objects, you compare the objects’ ____
instead of actual values.
a. reference fields c. Boolean values
b. primitive data types d. memory addresses
ANS: D PTS: 1 REF: 247
COMPLETION
1. ____________________ is a tool that helps programmers plan a program’s logic by writing plain
English statements.
ANS: Pseudocode
2. A(n) ____________________ structure is one that involves choosing between alternative courses of
action based on some value within a program.
ANS: decision
3. ____________________ statements are particularly useful when two conditions must be met before
some action is taken.
ANS: Nested if
4. Both & and | are valid Java operators, but they operate on ____________________ rather than making
comparisons in logical conditions as && and || do.
ANS: bits
ANS: if
MATCHING
SHORT ANSWER
ANS:
When computer programmers write programs, they rarely just sit down at a keyboard and begin
typing. Programmers must plan the complex portions of programs using paper and pencil.
Programmers often use pseudocode, a tool that helps them plan a program’s logic by writing plain
English statements. Using pseudocode requires that you write down the steps needed to accomplish a
given task. You write pseudocode in everyday language, not the syntax used in a programming
language.
ANS:
In a sequence structure, one step follows another unconditionally. A sequence structure might contain
any number of steps; but when one task follows another with no chance to branch away or skip a step,
you are using a sequence.
3. An alternative to using a Boolean expression, such as quizScore == 10, is to store the Boolean
expression’s value in a Boolean variable. How could you express this in Java?
ANS:
For example, if isPerfectScore is a Boolean variable, then the following statement compares
quizScore to 10 and stores true or false in isPerfectScore:
isPerfectScore = (quizScore == 10);
Then, you can write the if as:
if(isPerfectScore)
System.out.println("The value is 10");
4. Why would a programmer execute more than one statement that depends on the evaluation of a
Boolean expression, and how could he or she do it in Java?
ANS:
Often, you want to take more than one action following the evaluation of a Boolean expression within
an if statement. For example, you might want to print several separate lines of output or perform
several mathematical calculations. To execute more than one statement that depends on the evaluation
of a Boolean expression, you use a pair of curly braces to place the dependent statements within a
block.
5. Within an if or an else statement, how can you code as many dependent if statements as you
need?
ANS:
Statements in which an if structure is contained inside another if structure are commonly called
nested if statements. Nested if statements are particularly useful when two conditions must be met
before some action is taken.
6. Why would a programmer use an AND operator when using nested if statements?
ANS:
You are never required to use the AND operator because using nested if statements always achieves
the same result. But using the AND operator often makes your code more concise, less error-prone,
and easier to understand.
ANS:
A range check is a series of statements that determine within which of a set of ranges a value falls.
Consider a situation in which salespeople can receive one of three possible commission rates based on
their sales.
8. What is wrong with the following statement? How could you correct it?
if(payRate < 5.85 && payRate > 60)
System.out.println("Error in pay rate");
ANS:
As a single variable, no payRate value can ever be both below 5.85 and over 60 at the same time.
Therefore, the output statement can never execute, no matter what value the payRate has. In this
case, you must write the following code to print the error message under the correct circumstances:
if(payRate < 5.85 || payRate > 60)
System.out.println("Error in pay rate");
9. List and explain the keywords used with the switch statement.
ANS:
switch starts the structure and is followed immediately by a test expression enclosed in parentheses.
case is followed by one of the possible values for the test expression and a colon.
break optionally terminates a switch structure at the end of each case.
default is optionally used prior to any action that should occur if the test variable does not match
any case.
ANS:
You use the NOT operator, which is written as the exclamation point ( ! ), to negate the result of any
Boolean expression. Any expression that evaluates as true becomes false when preceded by the
NOT operator; and accordingly, any false expression preceded by the NOT operator becomes
true.
ANS:
In a single-alternative if structure, an action is performed, or not, based on one
alternative. Often, you require two options for the course of action following a decision. A dual-
alternative if is the decision structure you use when you need to take one or the other of two
possible courses of action. For example, you would use a dual-alternative if structure if
you wanted to display one message when a value of a variable is greater than 20 and a different
message when it is not. In Java, the if…else statement provides the mechanism to perform one
action when a Boolean expression evaluates as true, and to perform a different action when a
Boolean expression evaluates as false.
12. In Boolean expressions, when you want to execute more than one statement based on the results of the
expression, you place statements within a block. What is a block and why is it important in decision
statements? Why are curly braces crucial when blocking an if statement?
ANS:
To execute more than one statement that depends on the evaluation of a Boolean expression, you use a
pair of curly braces to place the dependent statements within a block. When you place a block within
an if statement, it is crucial to place the curly braces correctly. Curly braces are required if multiple
statements must be treated as a block. When you create a block, you do not have to place multiple
statements within it. It is perfectly legal to place curly braces around a single statement. For clarity,
some programmers always use curly braces to surround the actions in an if statement, even when
there is only one statement in the block.
13. Create an if statement that will check if the variable salesAmt is greater than the constant
SALES_QUOTA. If true, create a block statement that will calculate salesAmt * BONUS_PERCENT
and store the result in a variable named bonusPay. The block statement will then compute
totalPay by adding salesAmt to bonusPay. Outside of the if structure, add a println
statement that will output the totalPay value.
ANS:
if(salesAmt > SALES_QUOTA)
{
bonusPay = salesAmt * BONUS_PERCENT
totalPay = salesAmt + bonusPay
}
System.out.println(“Total pay is " + totalPay);
14. Create an if statement that checks if the variable salesAmt is greater than or equal to the
QUOTA_AMT constant. Use the logical OR operator to also check if salesAmt is greater than or
equal to the HIGH_SALES constant. If either expression is true, assign the value of the
LARGE_QUOTA constant to the variable bonusAmt.
ANS:
if(salesAmt >= QUOTA_AMT || salesAmt >= HIGH_SALES)
bonusAmt = LARGE_QUOTA;
Decision making can be used to control the allowed values in an object’s fields. In the above code, the
Student class contains two fields that hold a student number and a score. A constructor accepts
values for these fields as parameters. Write the code between the curly brackets that will determine
whether the value of num is less than the MAX_NUM constant. If true, assign the value of num to
studentNum. Otherwise, assign the value of MAX_NUM to the studentNum. Then check if the
value of score is less than or equal to MAX_SCORE. If true, assign the value of score to
studentScore. Otherwise, assign 0 to studentScore.
ANS:
if(num <= MAX_NUM)
studentNum = num;
else
studentNum = MAX_NUM;
if(score <= MAX_SCORE)
studentScore = score;
else
studentScore = 0;
CASE
1.
Using the above flowchart and code, why will the above statements execute but provide unintended
results?
ANS:
There should be no semicolon at the end of the first line of the if statement following the parentheses
because the statement does not end there. The statement should end after the println() call, so that
is where you type the semicolon. You could type the entire if statement on one line and it would
execute correctly. However, the two-line format for the if statement is more conventional and easier
to read. Therefore, you usually type if and the Boolean expression on one line, press Enter, and then
indent a few spaces before coding the action that occurs if the Boolean expression evaluates as true. If
you use the two-line format and type a semicolon at the end of the first line, as in the example shown
above, the results might not be what you intended.
In this example, when the Boolean expression is true, an empty statement that contains only a
semicolon executes. Whether the tested expression evaluates as true or false, the decision is over
immediately, and execution continues with the next independent statement that displays a message.
In this case, because of the incorrect semicolon, the if statement accomplishes nothing.
2. Write a single-alternative if statement that will check if a variable named maxValue is equal to 100.
If true, use a println statement to output “You have reached the limit”.
ANS:
if (maxValue == 100)
System.out.println ("You have reached the limit");
3. if (maxValue = 100)
System.out.println ("Your limit has been reached");
Why is the above if statement illegal? How would you fix it?
ANS:
A common programming error occurs when a programmer uses a single equal sign rather than a
double equal sign when attempting to determine equivalency. The expression maxValue = 100
does not compare maxValue to 100. Instead, it attempts to assign the value 100 to maxValue.
When the expression maxValue = 100 is used in the if statement, the assignment is illegal
because only Boolean expressions are allowed.
if(isLimitReached)
System.out.println("Your limit has been reached");
4. Create an if…else statement that will check if the maxValue variable is equal to 100. If true, create
a println statement that will output “Max reached”. If false, create a println statement to output
“Keep trying”.
ANS:
if(maxValue == 100)
System.out.println("Max reached");
else
System.out.println("Keep trying");
When you execute an if…else statement, only one of the resulting actions takes place
depending on the evaluation of the Boolean expression. Each statement, the one following the
if and the one following the else, is a complete statement, so each ends with a semicolon.
Why is the above code incorrect? What would be required to make the code execute correctly?
ANS:
When you place a block within an if statement, it is crucial to place the curly braces correctly. In the
above code, the curly braces have been omitted. When qtySold > QUOTA is true, bonusPay is
calculated and the if expression ends. The next statement that computes totalPay executes every
time the program runs, no matter what value is stored in qtySold. This last statement does not
depend on the if statement; it is an independent, stand-alone statement. The indentation might be
deceiving; it looks as though two statements depend on the if statement, but indentation does not
cause statements following an if statement to be dependent. Rather, curly braces are required if
multiple statements must be treated as a block.
When you create a block, you do not have to place multiple statements within it. It is perfectly legal
to place curly braces around a single statement. For clarity, some programmers always use curly
braces to surround the actions in an if statement, even when there is only one statement in the
block.
Because the curly braces are missing, regardless of whether qtySold is more than QUOTA, the last
statement in the sample code is a new stand-alone statement that is not part of the if, and so it
always executes. If qtySold is 80, for example, and QUOTA is 100, then the program calculates
the value of totalPay as a negative number (because 80 minus 100 results in -20). Therefore, the
output is incorrect. Correct blocking is crucial to achieving valid output.
6. if(firstValue == secondValue)
{
int total = firstValue + secondVaue;
System.out.println("The values are equal");
}
System.out.println("The total is " + total);
ANS:
When blocking statements, it is crucial to remember that any variable declared within the block is local
to that block. In the above code, a variable named total is local to the block following the if. The
ending println statement causes an error because the total variable is not recognized.
7. Write a nested if statement that will check if the variable qtySold is greater than the QTY_QUOTA
constant. If true, evaluate a second expression that will check if the variable totalSales is greater
than the constant SALES_QUOTA. If the second expression is also true, create an assignment statement
that will assign the constant BONUSAMT to the variable bonus. After BONUSAMT is assigned, the if
structure ends.
ANS:
if(qtySold > QTY_QUOTA)
if(totalSales > SALES_QUOTA)
bonus = BONUSAMT;
ANS:
if(salesAmt >= SALES_QUOTA)
if (salesType == HIGHVALUE)
bonusAmt = 500;
else
bonusAmt = 100;
else
bonusAmt = 0;
9.
Use the above flowchart to create the code using the logical AND operator to determine if a
FULL_BONUS will be assigned to the variable bonus.
ANS:
if(salesAmt > QUOTA && productType == HIGHVALUE)
bonus = FULL_BONUS;
10. Create a switch statement that will test the value of a variable named score. If score has a value
of 5, create a println statement that will output “Excellent”. If score has a value of 4, create a
println statement that will output “Great”. If score has a value of 3, create a println statement
that will output “Good”. If score has a value of 2, create a println statement that will output
“Fair”. If score has a value of 1, create a println statement that will output “Needs
improvement”. If score does not contain a matching value for any of the case statements, create a
println statement that will output “Retake test”.
ANS:
switch(score)
{
case 5:
System.out.println("Excellent");
break;
case 4:
System.out.println("Great");
break;
case 3:
System.out.println("Good");
break;
case 2:
System.out.println("Fair");
break;
case 1:
System.out.println("Needs improvement");
break;
default:
System.out.println("Retake test");
}
Maissa tämä temppu olisi tietenkin heti ollut linnun häviö. Ketterä,
jäntevä näätä olisi kääntynyt ympäri ja käynyt hampain kiinni
vastustajansa kurkkuun, jolloin taistelu olisi ollut lopussa. Mutta
täällä vedessä se ei saanut mitään tukea, minkä varassa ponnistaisi.
Se ei voinut muuta kuin potkia hyödyttömässä raivossaan. Sitäpaitsi,
tottumattomana kamppailemaan veden alla, se tahtomattaan avasi
suunsa ja samassa tunsi alkavansa tukehtua. Jos joutsen nyt
todellakin olisi ymmärtänyt asemansa edullisuuden, olisi se ilman
muuta voinut hukuttaa ahdistajansa ja näin vapauttaa erämaan
yhdestä sen pahimpia vitsauksia. Mutta vimmastunut lintu, joka ei
itse tuntenut mitään vastenmielisyyttä pitäessään päätään useita
minuutteja yhteen menoon veden alla, ei osannut aavistaa, että
sellainen koe olisi sen viholliselle ollut kuolettava. Se hellitti hetken
perästä kauhean otteensa ja jäi keveästi peräytyen odottamaan
hyökkääjän uutta ilmestymistä veden pinnalle, torjuakseen sen
uusilla iskuilla suurista siivistään, joihin se alati turvasi.
Meren tiikeri.
Halki laajojen, hiljaisten punavihreiden maininkien, joiden harjaa
lempeä tuulenhenki heikosti väreilytti, uiskenteli emovalas
tyytyväisenä poikasen pysytellessä aivan vieressä. Vähän väliä
pikku valas hankasi itseään emoa vastaan ikäänkuin arkaillen noita
valtameren aavoja ja vaarallisia ulapoita ja etsien suojaa emon
lyhyen, voimallisen pyrstön takaa. Ja vähän väliä emovalas, joka on
villin luonnon huolellisimpia ja uutterimpia äitejä, veti poikasensa
isolla pyrstöllä hyväillen kylkeänsä vasten tai kääntyen puoleksi
ympäri kosketti sitä kysyvästi suunnattomalla pyöristetyllä
kuonollaan.
Valaan poikasella ei ollut juuri syytä tuntea pelkoa, niin kauan kuin
se pysyi emon läheisyydessä. Sillä tämä valaista vinhavauhtisin ja
julmin ei pelännyt mitään muuta uivaa kuin jättiläisserkkuaan
potovalasta. Vaikka vain kahdenkymmenen jalan pituinen, saattoi se
pelkän vimmansa nojalla tehdä hengenvaarallisia hyökkäyksiä
suurta eli "oikeata" valasta vastaan, joka oli noin neljä kertaa sen
pituinen ja monin verroin kookkaampi. Ihmistä sen olisi ehkä ollut syy
peljätä, jos se olisi koskaan joutunut tämän mahtia kokemaan, mutta
kun se oli rasvasta köyhä, ei sen suku koskaan ollut houkutellut
ihmistä näin vaivaloiseen ja vaaralliseen pyydystämiseen. Haikaloja
tosin oli sen kokoisia tai siitä voiton viepiäkin, mutta ei ainoatakaan
sen vertaista julmuudessa, nopeudessa ja oveluudessa.
Huolettoman tyytyväisenä se siis uiskenteli pitkin suloista, rauhallista
merta, välittämättä hyrskyistä keltaisten kallioiden ympärillä oikealla
puolella tai valtameren tyhjistä avaruuksista vasemmalla. Mikäli
aikaa jäi poikasen lapsellisen sulon tarkkaamiselta, sen se käytti
tähystelläkseen läpikuultavaan syvyyteen allaan; siellä piileskeli
suuria mustekaloja ja muita velttoja merenpohjalla eleskeleviä kaloja,
joita sen oli tapana saaliikseen pyydystää.
Mitä tulee varsinaiseen taisteluun, niin tämä oli sen loppu. Useita
minuutteja kesti tuota jättiläistemmellystä, joka pieksi värjäytyneitä
vesiä yardien korkeuteen, mutta se oli vain toispuolista, kun
miekkavalas pudisteli ja murskasi ja repi henkeä irti voitetusta
vastustajastaan. Vihdoin se vetäytyi pois jättäen ruhjotun raadon
hitaasti painumaan syvyyksiin. Sitten se kahmaisi kiihtyneen
poikasen evänsä alle, imetti sitä ja ui hitaasti maata kohden saaria ja
rantaa tällä kohtaa erottavaan syvään salmeen, missä luuli
löytävänsä lisää noita meheviä mustekaloja korvaukseksi siitä, joka
niin arvaamatta oli välttänyt sen lähentelemiset.
Mutta vaikka Gardner oli tottunut purjehtija, jolla oli tarkka silmä
huomaamaan kaikki säänmerkit ja herkkä vaisto tuntemaan
tuulenpuuskat ruorinvarresta tai purjeen jännityksestä, oli hän
luonnonhistoriaan vähemmän perehtynyt, kuin oli suotavaa
sellaiselle, joka piti asutettua merta urheilukenttänään. Hänen
käsityksensä valaiden suvusta ja niiden vaihtelevista luonteista
perustui siihen, mitä oli lukenut suuresta pelokkaasta valaanluu-
valaskalasta ja nähnyt iloisesta, vaarattomasta pyöriäisestä. Kun hän
nyt näki miekkavalaan kaarevan mustan selän ja kauhistavan pään
sen verkalleen kyntäessä aaltoja, ei hänen siis juolahtanut
mieleensäkään, että piti olla varuillaan. Jos hän olisi ollut tavallinen
kulkija näillä vesillä, olisi hän heti kääntänyt keulansa toiseen
suuntaan, jottei valas arvelisi hänen haluavan häiritä sen
yksinäisyyttä. Mutta näin ollen hän purjehti lähemmäksi nähdäkseen,
mikä kala tai peto tuo musta ja valkoinen olento oli, se kun ei
näkynyt olevan hänen lähestymisestään milläänkään.