Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

LoopStructuresand Strings

oop structures,countersand accumulators, and flags are explained


in this chapter.Debugging techniques and the String class are also
discussed.

Ioop structure The statementis aloopstructure,


which executesa setof statements
"hi-le
over and over again based on a condition. Loop structures are used to
perform taskssuch as summing a set of numbers as they are enteredby
the user or repeatedlyprompting the user for a value until valid data is
entered.The while statementtakesthe form:
while (<conclition>) {
< statsements >
]
The condition of the whili loop is a Boolean expression, which is evaluated
before the statements are executed. When the condition is true the state-
ments are executed, when the condition is false program flow continues to
the next statement after the closing curly brace of the Each execution
"hil..
iteration of the loop is called an iteration.Note that ? while loop may never execute
if the condition initially evaluates to false.

The following while statement executes five times:

Nesfed Loops int num = 0;


while {num < 5) {
A loopstructure cancontain
num += 1;
anotherloop structure. Loops
]
placedwithin a loop arecalled
nested loops. Eachtime the After the fifth executior! numis equal to s, making the condition false.
outer loop iterates,the inner
loop iterates
untilitscondition
is met.

The do-wh:-lestatement is an alternative form of the statement. In


"hile
the do-whi1e statement the condition is not evaluated until after the first
execution of the loop. Therefore, the do-while executes at least once.

The do-whi1etakes the following form:

do{
<s E a t e m e n t s >
] while (<condition>);

Chapter6 Loop Structuresand Strings


The following ilo-whi1e example prompts the user until a valid number
is entered:
do{
Systen.out.print("Enter a nurnber less than 4:");
playerNum = input.nextlnt0 ;
i while (playerNum >= 4);

The condition of a loop is used to determine when the loop should stop
executing.A while continuesuntil its condition is false.What happens,
though, if the condition never becomesfalse? The result is an infinite
loop-one which continues forever. For example,the following generates
an infinite loop. Can you seewhy?
int num = -1;
while (nurn < 0) {
num = -1;
]
The code causesthe application to simply stop responding or just "hartg."
When this happens,closethe output window to end the application. Note
that some compilers may require a different procedure to end an infinite
loop.
Syntax errors are a common causeof infinite loops. For example, a
semicolonafter the condition causesthe statementto check the condition,
do nothing, check the condition, do nothing, and on and on:
while (num < 0); { //an infinite loop here--added semicolon
num += 1;
]
Another exampleof a syntax error that can lead to an infinite loop is
omitting the curly braces:
while (nun < 0) //an infinite loop here--no braces
System.out.print("Enter a value: ");
num = input.nextlnt0;

In this case, only the first statement is executed &nd nun is never assigned
the input. Although properly done, the indentation makes it difficult to
find the syntax error.

A logic error can also lead to an infinite loop condition. For example, in
the code below nun is initialized to 1 and never decremented to a number
less than 0 in the loop, making the condition of the loop structure always
true:
int nun = 1;
do{
num += 1;
] while (num >= 0);

In this case, the loop isn't infinite because numis eventually assigned a
overtbw number so large that an overflow results. An oaerflow occurs when there
are not enough bits to store a number. This may generate a run-time error
or, in the case of the code above, actually cause the condition to become
false. An overflow changes the sign of the number stored.

Chapter6 Loop Structuresand Strings


Createa Prompter application that prompts the user for two numbers. The first number is a min value and
the secondis a max value. Prompter then prompts the user for a number between the min and max numbers
entered. The user should be continually prompted until a number within the range is entered. Be sure to
include the min and max numbers in the prompt.

Many algorithms require counting and summing values. For example,


an applicationthat calculatesthe averageof a set of numbers must sum
the numbers and then divide the total by the count. The AverageValue
application performs counting and summing. A run of the application
looks similar to:

Enter a ualue (0 to quit): 25


Enter a ualue (0 to quit): 14
Enter a ualue (0 to quit): 18
Enter a ualue (0 to quit): 22
Enter a ualue (0 to quit): 30
Enter a ualue (0 to quit): 0
A u e r a g ei s 2 1. 8

The AverageValue
applicationis basedon the pseudocode:
Promnt rrser for a value
while (va1ue != 0)
count value
add value to sum of values
pronpt user for another value
Display average of values (sum/count)

A program that counts the number of values entered by the user is


actually counting the number of loop iterations. To count loop iterations,
a statementsimilar to the following is used within the loop:
numValues += l-;

Eachtime the statementexecutes,one is added to the current value of the


variable.This type of variable is called acounterbecauseit is incremented
by a constant value. Counters are useful for keeping track of the number
of times a user enters a value, makes a guess,or types a password. A
counter should be initialized when it is declaredand then incremented
by a fixed amount.
A similar assignment statement is used to sum values as they are
enteredby the user:
sumOfValues += newvalue;

Each time the statementexecutes,the value of newValue is added to the


current value of the variable. This type of variable is called an accumulator
becauseits value "accumulates."As with a counter,an accumulatorshould
be initialized when it is declared.

Chapter6 Loop Structuresand Strings


The AverageValue code includes both a counter (numValues)and an
accumulator (sumOf
Values):

/* AverageValue application. */

import java. uti1. Scanner;

* Jlisnlavs thc aver-de of a set of numbers

public class AverageValue {

public static void main(String[J args)


final int SENTINEL = 0;
i - L - ^ . . \ 7 ^ 1 . . ^ .

int nunValues = 0;
int sum0fValues =0;
. 1 ^ , ], " 1- - - , ^ .
Scanner input = n e w S c a n n e r ( S y s t e m .i n ) ;

/* Get a set of numbers from user *,/


System.out.println("Calcu1ate Average Program") ;
System.out.print("Enter a value (" + SENTINEL + " fs^v ^,,its1.
94rL/.
" 1/ .,

newValue = input.nextlnt0;
while (newValue != SENTINEL) {
nunValues += 1;
sum0fValues += newValue;
r r \ .
System.out.print("Enter a value(" + SENTINEL + " F ^
L v
^ . . a F \ .
Y q 4 s / . / |

newValue = input.nextlnt0;
]
input. close ();

/*Calculate average of numbers entered by user */


avg = (doubJ-e)sum0fValues / (ilouble)nurnValues;
System.out.println("Average is " + avg);

The AverageValue codeusesa constantnamed SENTTNEL. This constant


flag, sentinel storesa value to act as a flag, or sentinel,to signify that the loop should
stop iterating. AverageValuedefines the sentinel with a constant.Another
approach is to use a variable and prompt the user for the sentinel value.

Createan Evensapplicationthat displaysthe evennumbersbetweenL and 20,inclusive.

Createa NumbersSum application that prompts the user for a number and then displays the numbers 1
through the number entered,each on a separateline. Below the numbers, the sum is displayed.

applicationthat prompts the user for a set of scoresand then calculatesthe percent-
Createa PercentPassing
ageof scoresabove70%.The user should have the option to enter as many scoresas needed.(Hint: Use an
if statementand anothercounter.)

Chapter6 Loop Structuresand Strings


The for statement is a loop structure that executes a set of statements a
fixed number of times. The for statement takes the form:
for (<initialization>; <condition>; <increment>) {
<statements >
]
The initialization is performed only once when a for statement is executed.
The condition is a Boolean expression, which is evaluated before each loop
iteration. When the condition is true the statements are executed, when
false, program flow continues to the next statement after the closing curly
brace of the for. After each loop iteration, the increment is executed.

loop control variable The following statement uses a counter to control the iterations of a for
statement. The counter i is the loop control oariable.When i is greater than
10,looping terminates:
T I P C o u n t e rv a r i a b l e si n a for (int i = l-; i <= 10; i++) {
f o r l o o p a r e o f t e n n a m e di , System. out. println (i) ;
j, or k.
]

Note that the counter is declared in the initialization of the for statement
scope (i"t i = 1). With a declaration in this location, the scopeof the counter
is from the initialization to the closing curly brace of the for statement.
The application will not recognize the variable outside of that statement.
programming style Declaring variables so that their scope is limited to where they are needed
is good programming style because it produces cleaner code and helps
eliminate the possibility of errors.

The statement above uses the ++ operator in the increment part of the
increment operator for statement (i++). The ++ operator is called the increment operatorbecause
it increases the value of a variable by 1. The ++ operator is a good choice
in the increment of a for statement because the effect is to increase the
operand by 1. However, ++ should not be used within an expression, such
ExpressionsUsing++ as i++ <= 1-0,because the value returned by the operator is used in the
or -- expression, not the final value of the operand.

lf the ++ or -- operator Any combination of components can be left out of a for statement. This
appearsbeforethe operand, can be useful when a counter is declared and initialized outside the state-
it is calledprefix(i.e.++i). An
ment, as in the following code:
operatorafterthe operandis
calledpostfix(i.e.i++). Either rnc num;
o p e r a t o rl o c a t i o nh a s t h e System.out.print("Enter the starting number: ");
sameeffecton the final varue nuro = input.nextlnt0;
o f t h e o p e r a n d .H o w e v e r , for (; nun <= l-0; num++) {
i n a n e x p r e s s i o nt ,h e p r e f i x qvcf6h ^,,f hri.f1. 1."-l .

versionusesthe valueof the ]


operandafter the operation.
F o r e x a m p l ew , henx is 12, A for statementmay also count down from a start value to an end value
the statement++x returns13. operatoL--i
using the decrement
I n t h e p o s t f i xv e r s i o nx, + + , (int
for countDown = 10; countDown <= 0; countDown--) {
12 is returnedT . h e r e f o r ea, (c o u n t D o w n ) ;
S y s t e m . o u t . .p r i n t l n
statement suchasx++ >= 13 is
]
falseandcouldbe ambiguous.
Usingthe ++ and -- operators While it is possibleto modify a loop control variablefrom within a for
i n a n e x p r e s s i o ni s p o o r loop or to terminatea loop prematurely,this is consideredpoor program-
programming style.
ming style. Good programming style dictates that changesto the loop
control variable occur in the increment portion of the loop only and that
the loop end only when the condition is false.

Chapter6 Loop Structuresand Strings


Createa Factorial application that prompts the user for a number and then displays its factorial. The factorial
of a number is the product of all the positive integers from 1 to the number. For example,5t = 5*4*32*7.

Createan OddSum application that prompts the user for a number and then sums the odd numbers from 1
to the number entered.

T I F I o b u g "i s a n e r r o ri n a The source of bugs, which are often logic errors, can be hard to deter-
proSram. mine without tools for debugging an application. Debugglngis the process
of getting an applicationto work correctly.One tool included with many
compilers is called a debugger.

debugger A debuggeris used to selectstatementswhere execution will be sus-


breakpoints pended. Thesestatementsare called breakpoints.
Application output goes
to a Debug Window and statementscan be executedone at a time between
breakpointsby using a Stepcommand.When stepping through an applica-
tion, selectedvariables are displayed in a Watch window along with their
value. When a watch variable is assigneda new value, the Watch window
is updated.Steppingthrough codeand watching variablescan an effective
way to determine logic errors.
Another debugging tool is called a variable trace and is done manu-
variable trace ally. A aariabletraceis a table listing the values of variables at the points
of assignment.For the following code,nunl drd num2would be included
in a variabletrace:
int numl = 0;
int num2 = 0;
while (nun1 < i-0) {
T I P A c o m m o n e r r o rw i t h if (nun1 t 3 == 0) {
l o o p s r s a n o l l - D y - o n ee r r o r . num2 += numl;
Thisoccurswhen a loop iter- System.out.print(num2 + " ");
atesone too many or one too ]
f e w t i m e sd u e t o a B o o r e a n numl += 1;
expresston error. ]
The variables are listed in the order that assignment occurs within the
loop. Output is also listed to better understand the code:

num2 oufpuf numl


0 tl 1
2
3
3 3

E
6 L] 7
I
s
s s 1!

Chapter6 Loop Structuresand Strings


additional println0 A third debugging technique involves adding additional println0 state-
ments to an application. Adding println0 statements just after a variable is
assigned a new value or before and after a condition is evaluated can help
detect the source of a logic error. For example, the code segment below
includes additional statements for debugging:
int numl- = 0;
int num2 = 0;
System.out.println("nun1 before while: " - 1 -- " - 1 \ ' //A^1,,^
while (num1 < 10) {
System.out.printl-n("numl- in whil-e: " + numl); //debug
if (nunl- % 3 == 0) {
num2 += numl;
System.out.println( " n u m 2 :" + n u m 2 ); //debws
System.out.println(num2 + " ");
]
numl += 1;
]

When run, the code above displays the following output, which can be
compared to the values expected. Note the similarity to a variable trace:

numl before Hhile: 0


numl in r.rhil.e: 0
numZ :0
0
numl in Hhile: 1
nunl in Hhile: 2
numl in Hhile: 3
nun2:3
3
numl in r.rhile:4
numl in uhile:5
numl in r.rhile:6
n u m 2I:
I
numl in HhiIe: 7
numl in HhiLe: I
numl in nhile:9
n u m 2I:I
18

commenting out code Commenting out statementscan be an effective way to locate a bug
through processof elimination. Typically the / / charactersare easiestto
type at the beginning of a statementto 'tomment it out."

Using paper and pencil, createa variabletracefor the following code,tracing the valuesof nun1,num2,
i, and
any output:
int numl- = 0;
int num2 = 0;
for (int i = 0; i <= 4; i++) {
nurnl=ixi;
num2 += numl-:
Svsfem nr)j- nrintlnuml + ");
]
System. out. println ( n u m 2) ;

Chapter6 Loop Structuresand Strings


Primitive data types such as int ?nd doubleare used for storing numeric
data. However,when data is comprised of a sequenceof characters,a data
type for storing strings is needed.|ava includes the string classin the
java.langpackagefor storing and manipulating strings.The string class
is large, with numerous methods for string manipulation. Some of the
String classmethodsinclude:
ClassString(java.lang.string)
Methods
lensth 0 returns an integercorrespondingto the number
of charactersin the string,
More on Concatenation substring(int start, int encl)
A s i n t r o d u c e di n C h a p t e r4 , returns a substring of the string, which starts
c o n c a t e n a t i oa n p p e n d so n e of starr position and endsone characterbefore
s t r i n gt o a n o t h e r W . hen the the endposition.
+ o p e r a t o ri s u s e d t o j o i n a
substring(int start)
stringand a ntin{bric,the com-
p i l e r f i r s t c O n v e r t sa n y n o n - returns a substring of the string, which starts
S t r i n gd a t at o a S t r i n go b j e c t ?t starr position and extendsto the end of the
beforejoiningthe strings. The string.
S t r i n gc l a s sa l s oc o n t a i n st h e tolowerCase
0 returns a copy of the string with all lowercase
c o n c a t ( )m e t h o df o r j o i n i n g Ietters.
two strings.
toUpperCase
0 returns a copy of the string with all uppercase
letters.
trin () returnsa copyof the string with all leading and
trailing spacesremoved.
replaceFirst(String str, String str2)
returns a string with the first occurrence of srr
replaced by =t'2.
replaceAll(St.ring str, Strj-ng st12)
returns a string with all occurrences of srr
replaced by
"t'2.
index The position of a character in a string is called its index. The first char-
acter of a string is at index 0. The last character of a string is at index
length0 - 1. The MiddleThree class below displays the three letters in the
middle of a string:
public class MicldleThree {

nrrhl in ef^f i. rrni.i --i-lqf -i-^f l --^-\ J


\wurrug LJ ar95/ I

Stri no nhrase throoT arfarc.

inf nLrrcal.ararL.

int rnid;
Scanner input = new Scanner(System.in);

/* get string fron user */


System.out.print("Enter text that contains at least
three characters: ");
phrase = input.nextline0;
input. cl-ose { );

/* determinemiddle of phrase */
phraselengtfi
= phrase. length() ;
mid=phraseLength/2;

Chapter6 Loop Structuresand Strings


/* display niddle three characters */
threeletters = phrase.substring(mid - 1, nld + 2);
System.out.println("Middte three characters are:
+ threeletters):
]
]

Note that the String objects (phrase,rhreeleter") can be declared in the


same way primitives are declared-the data type followed by the vari-
able name. With the String class, the following two statements perform
the same task:
String alpha = new String("abc"); //these assignments are
String alpha = "abc"; //efffectlve1y the same

The MiddleThreeapplicationproducesoutput similar to:

Enter text (at least three characters): abcde


Hiddle three characters are: bcd

immutable A string is said tobe immutablebecatse it cannotbe changed.Methods


that manipulate the original string, for example tolowerCase0, create
a new string in memory becausethe original string cannot be changed.
Assigning a new string to a String objectsimply changesthe objectrefer-
enceto point to the new string in memory. For example,the following code
generatesa new string. Assigning the string to the text objectchangesthe
obiect'sreference:
text,
SfTi hd f6vf.
|Iffi-]
text
text
= "hel10";
= text.tolowerCase0;
System. out. println

The codeproducesthe output:


(t e x t ) ; ru
tt

heIIo

null Until a String object is assigned a value, it refers to nu11.Calling a method


NullPointerException from a null String object generates the exception NullPointerException.

Createan AccountSetupapplicationthat prompts the user for a user name and a password.The application
should prompt the user until a passwordwith at leasteight charactersis entered.The user name and pass-
word should be convertedto all lowercaselettersand then an appropriatemessagedisplayed.Application
output should look similar to:

Enter a user name: IIHIUilID


Enter a passi.forfd that is at least I characters: fiuess
Enter a pass$rold that is at least I characters: Frogramner
Vour user nane is r+hizkid and your" passuond is programnen

Chapter6 Loop Structuresand Strings


Strings are comparedwhen determining equality or alphabeticalorder.
In chapter5, relational operators,including ==and >,were used to compare
primitive types. When objectsneed to be compared, methods from their
classare used. Someof the String classmethods for comparing strings
include:
ClassString(java.lang.String)

Methods
equals(String str)

returns true when the string is the sameas srr.


Returnsfalseotherwise.
a
udY lur u^ 4
1 r. T
f Yd u. ^v -r au lv^o- s- ^E /cr-r -- -ts-l
\rLrrug sLr/

Unicode same as equals0 exceptthat uppercaseand


The UnicodeStandardis lowercasedifferences between the strings are
ignored.
a 16-bit encoding system
conpareTo(String str)
that assigns a value for
eachcharacterand symbol returns 0 when str is the sameas the string, a
of every language. |ava negative integer is returned when comes
"tr
alphabeticallyafter the string, and a positive
uses this standard when
integer is returned when .t' comes alphabeti-
defining strings, and cally before the string. Note that uppercaseand
String classmethods use lowercaseletters are considered different,
the charactervalues when .nm-^.oT^T-.^TAC^<a /Sr.i rn <trl
comparing strings.
sameascompareToQexceptthat uppercaseand
lowercasedifferencesbetween the strings are
ignored.
indexOf(Strinq str)

returns the integer corresponding to the


location of the first occurrenceof str in the
string. Otherwise -1 is returned.
lastlnilex0f (String str)

returns the integer corresponding to the


location of the last occurrence of str in the
string. Otherwise -L is returned.
startsWith (Strinq str)

,*rrrn, true when the string begins with srr.


Returnsfalseotherwise.
endsWith(Strinq str)

returns true when the string ends with str.


Returnsfalseotherwise.

The AlphaOrder classcomparestwo strings and then displays them in


alphabetical order:
public class Alpha0rder {

public static voiil main(String[] args) {


String worill, woril2;
Scanner input = new Scanner (System.in);

Chapter6 LoctpStructures
and Strings
System. out.print ( "Enter a w o r d . : " ) ;
worcll- = input.nextline 0 ;
System. out. print { "Enter a second woril:
woril2 = input.nextline0;
'i nnrrt n'l aea / I '

if (wordl.cornpareTolgnoreCase(word2) == 0) {
System.out.println("Worils are equal.");
] else if (worill.compareTolgnoreCase(word2) < 0) {
Systern.out.println("In alphabeticaf order: " + r+ord1
+"u+worcl2);
) else {
System.out.prj-ntln("In alphabetical orcler: + word2
+u"+wordl);
]
]
i
AlphaOrder produces output similar to the following:

Enter a Hord: bear


E n t e r a s e c o n dH o F d : a l l i g a t o r
In alphabetical order: alligator bear

Createa FormalGreeting application that prompts the user for his or her name, including title. The applica-
tion should display "Hello, sir." if the string startswith I'1r.,"Hello, mahm." if the string startswith u=.,ur=.,
or Miss,and "Hello, name."otherwisewhere nameis the user,sname.

In this casestudy, a word guessing game will be created.The word


guessing game allows the player to guessthe letters of a secret word. At
the start of the game,the player is shown only how many letters the word
contains through a set of dashes.when a letter matching one in the word
is guessed,it replacesthe appropriatedash.Play continues until the entire
word is guessedletter-by-letter or when the player choosesto guess the
entire word.

WordGuessSpecification
WordGuess is played between the computer and a single player. The
secretword is BRAIN. At the start of the game, six dashesare displayed
(------), onefor eachletter of the word. The player is repeatedlyprompted
for a letter guess.When a letter matching one in the word is guessed,the
letter replacesthe corresponding dash. Letters may be entered as upper-
caseor lowercase.Howevet only uppercaseletters should be displayed. If
the player entersan exclamationpoint (!), the player is prompted to guess
the word. At that point the player either wins (a correct guess)or loses
(an incorrect guess).Alternatively, the player can continue to guessletters
until the entire word is revealed.The games ends by showing the player
the total number of guesses.

Chapter6 Loop Structuresand Strings


The WordGuessinterface should display a row of dashes,one dash for
eachletter in the word. Promptsshouldbe used to get letter guessesfrom
the player. As corresponding letters are guessed,the letter is displayed
instead of the dash.At the end of the game,the user should be shown the
word along with the number of guesses.
The WordGuessoutput sketch:

WorAGuess
aame.

EnIer a lelter (l lo queeoentire word):a


--A--
E n L e ar l e l t e r ( l N o7 u e e ee n l i r e w o r d ) t v
--A--
EnNera lelNer(l NogueooenNireword):I
--A--

WhaNie your queee?


brain
Youwonl
ThesecreNword ie FRAIN
Youmade3 queeeee,

The WordGuessalgorithm:
1. Display a row of dashesto representthe word.
2. Prompt the user for a letter guess.
3. If the letter guessedis part of the word, then display that letter in
place of the corresponding dash.
4. Repeatsteps2 and 3 until all the lettershave been guessedor an
exclamation point has been entered by the user.
5. If an exclamationpoint hasbeenentered,prompt the user to guess
the entire word.
6. If the player correctly guessesthe entire word or all the letters have
been guessed,then display a messageindicating that the player
has won, otherwise the messageshould indicate that the player
has lost.
7. Display the secretword and the number of guesses'

andstrings
chapter6 Loop structures
n
The WordGuessflowchart:

lncremenl
queescounT,er

Oel wordque6a
rrom ?Eye?

"Youlose"
me99aqe

DioplayeecreNwordand
numberof auessesNaken

Chapter6 Loop Structuresand Strings


WordGuessCode Design
The input for WordGuessare letters typed by the user. A String vari-
able to store the player's letter guesswill be needed.The player may also
chooseto guessthe entireword, so anotherString variableto storea word
guesswill be needed.
The output for WordGuessis the secretword displayedas dashesand
then redisplayedwhenever a dash should be replacedby a letter, a prompt
for the user'sguess/a messageindicating a win or loss, and a message
indicating the secretword and the number of guessesmade.
Data generatedby WordGuessis a count of the number of guessesmade
by the user. A counter variable to store the number of guesseswill be
needed.Other data used in this application can be representedby String
constantsto representthe secretword (SECRET_WORD)and to use as a
loop sentinel(FLAG).A String variablewill also be neededto "build" a
new string that contains any correctly guessedletters.
Basedon the algorithm and flowchart, the codedesignfor the WordGuess
applicationwill include a loop structure to comparethe user'sinput to
the letters in the secretword. The best loop structure will be d do-while
becauseunder any condition the loop statementsshould iterate at least
once.It also unknown how many times the loop statementsshould iter-
ate,so a type of while statement,not a for statement,should be used.This
comparisonwill be done with an if statement.A pseudocodealgorithm
for WordGuessfollows:
Genarafc an'l
qrru diqrl--- ^ -'- -E r^^L-- -hat renresenr the word
utrPray uuqs !e!+eJe

do
rrndaFe drcssFs counLer
Promnt- rrser fnr: a letter
Convert to all uppercase
Determine if letter is in word
if letter
is in woril
Create new string that contains the guessed letter
while (al1 letters haven't been guessed and user hasn't chosen
to guess the entire worcl)
if ( ! has been entered)
get a word guess from player
convert woril to all uppercase
if (word guessed equals secret word 0R all- the letters have
been guessed)
display message that pJ-ayer has won
else
rii enl:rr th:t nl errcr hac Inqr

Display secret word


Display number of guesses

WordGuessImplementation
Basedon the codedesign,the WordGuessimplementationfollows:

* WordGuess.java

imDort iava.utsil-. Scanner;

Chapter6 Loop Structuresand Strings


* Plays a woril guessing game with one player.

public class WorilGuess {

public st.atic void main(String[] arqs) {


+ i n ^ ] q + r i - ^ c E C R E T W o R D= " B R A I N ' , ;
final String FLAG = "!";
String worclSoFar = "", upclateilWorcl = "";
String letterGuess, worilGuess = "";
int nunGuesses = 0;
Scanner input = new Scanner(System.in);

/* begin game */
System. out. println ( " W o r i l G u e s s g a m e .\ n " ) ;
for (int i = 0; i < SECRET_W0RD.1ength0; i++) {
wordSoFar += "-"; //word, as dashes
)
System.out.println(worclSoFar + "\n") ; //clisplay ilashes

/* a11ow player to make guesses */


do{
Systetn.out.print("Enter a letter (" + FLAG + " to guess entire worcl): ");
letterGuess = input.nextline0;
letterGuess = letterGuess.toUpperCase 0 ;

/* increment number of guesses */


numGuesses += 1;

/* player correctly guessetl a letter--excract string in wordSoFar


* up to the letter guessed. and then append guessed. letter to that
* string Next, extract rest of wordSoFar ancl append after the guessed
* letter

if (SECRET_WORD.inclexOf(letcerGuess) >= 0) {
updateclWord = worclSoFar.substring(0, SECRET W0RD.indexOf(letterGuess));
updateclWord += lettercuess;
updateilltloril += worilSoFar.substring(SECRET WORD.inclexOf(letterGuess)+1,
worclSoFar. length ( ) ) ;
worclSoFar = upilateclWord;
]

/* display guessed letter instead of clash */


System.out.println(worilSoFar + "\n");
] while (!letterGuess.equals(FLAG) && !wordSoFar.equals(SECRET WORD));

/* finish game anil display message anil number of guesses */


if (letterGuess.equals(FLAG)) t
Systern.out.println("What is your guess? ");
wordGuess = input.nextline 0 ;
word.Guess = woralcuess. toUpperCase 0 ;
]
if ( w o r d G u e s s . e q u a l s ( S E C R E T _ I I I O R D )l l w o r d S o F a r . e q u a l s ( S E C R E T _ W O R D ) ) {
System. out.println ( "You won! " ) ;
] else {
System.out.println("Sorry. You 1ose.");
i'
System.out.println("The secret word is " + SECRET_WORD);
Systen.out.println("You naale " + numGuesses + " crra<ca< "l'

Chapter6 LoopStructures
and Strings
E
A run of WordGuesslooks similar to:

U o r d G u e s sg a n e .

Enter a letter (! to guessentire nord)


--A--

Enter a letter ( ! to guess entire nord)


--A--

E n t e r a l e t t e r ( ! t o g u e s se n t i r e r . r o r d )
B - 4 .-

Enter a letter ( | to guess entire nord)


B.A.N

Enter a letter ( ! to guess entire r.rord)


B-R.N

ldhat is gour guess?


brain
Vouuon!
The secret uord is BRAIN
V o u m a d e5 g u e s s e s .

WordGuessTesting and Debugging


This casestudy should testall possibleguesscombinations.For example,
the player may enter an exclamationpoint on the first guess.Testing
should also include incorrect word guesses.

Modify the WordGuessChapter6 CaseStudy to display a scoreat the end of eachgame.The player should
start with 100points and have 10points taken off for eachguess.The scoreshould be updated and displayed
as the game is played. Display a player losesmessageif the scoregets down to 0.

This chapterintroducedloop structuresand the String class.The *hil.


statementand do-whilestatementare loop structuresthat iteratea set of
statementsrepeatedlybasedon a condition. The differencebetween the
loops is when the condition is evaluated. The statement evaluates
"hi1.
the condition before any iterations are performed. The do-while does not
evaluatethe condition until after the first iteration.

Chapter6 Loop Structuresand Strings


Some syntax errors and logic errors can lead to an infinite loop which
executes forever causing the application to just hang. A logic error can also
cause an overflow, which occurs when there are not enough bits to store
a number.

Counters are used for keeping track of loop iterations and are used
in applications that keep track of the number of guesses or the number
of values entered. An accumulator is increased by varying amounts.
Accumulators are often used to sum values. Both counters and accumula-
tors should be initialized when they are declared.

A flag, also called a sentinel, is used to signify that a loop should stop
iterating. Flags are usually a constant that is declared in the application,
but may also be determined by prompting the user for a value.

The for statement is another loop structure. This loop structure executes
a set of statements a fixed number of times. A loop control variable is used
to determine loop iterations and can be declared in the f"' statement itself.
When a variable is declared in a statement, its scope is limited to the open-
ing and closing curly braces of that statement. The increment operator (++)
and decrement operator (--) are used to increase or decrease the value of
a for loop control variable.

Debugging techniques include using a debugger, often included with


a compiler, and a variable trace, which is a manual technique. Debuggers
have the advantage of being able to display the actual value of a variable
as it changes. Other techniques include adding println statements before
and after variable assignment. Commenting out statements can also locate
an error through process of elimination.

The String class is used to declare string variables. It contains numerous


methods for determining the length of a string, converting a string to low-
ercase or uppercase characters, extracting substrings, and for comparing
strings. A string is immutable, which means it cannot be changed from
its original value. However, a String object can be assigned a new string
in memory. The characters of a string have an index value, with the first
character at index 0.

Code conventions introduced in this chapter are :


r The statements of an *hil" statement should be indented.
o The statements of a do-whi1estatement should be indented.
. The statements of a for statement should be indented.
r Declare variables so that their scope is limited to where they are
needed.
. Changes to a loop control variable should occur in the increment
portion of the loop only, and the loop should end only when the
condition is false.

Chapter6 LoopStructuresand Strings


Accumulator A variable that is incrementedby Iteration The executionof a loop.
varying amounts.
Loop control variable A counter that is used to
Breakpoint A statementselectedwhere execution control the number of for loop iterations.
will be suspended.
Loop structure A statementthat executesa set of
Counter A variable that is incremented by a fixed statementsrepeatedly based on a condition.
value.
NullPointerException exception An excep-
Debugger A tool included with some compilers tion thrown when operationson a null String are
for debugging. attempted.
Debugging The processof getting an application Overflow A condition that occurs when a number
to work correctly. is too large to be stored in a specified number of
bits.
Decrement operator The -- operator/which
decreasesthe value of a variableby 1. Sentinel A constantthat storesa value that is used
to signify that a loop should stop iterating. Also
Flag seeSentinel.
called a fIag.
Immutable Unable to change.
Scope Thesetof statementsthat canaccessa declared
Increment operator The++operator,which increases variable.
the value of a variableby 1.
Variable trace A table listing the values of vari-
Index The position of a characterin a string. ablesat the points of assignment.Used for manually
debugging an application.
Infinite loop A loop that continues forever.

++ The increment operator.

-- The decrement operator.

do-whi1e A loop structure that executes a set of


statements over and over againbased on a condition,
which is evaluated after an iteration.

f or A loop structure that executesa set of statements


a fixed number of times.

while A loop structure that executes a set of state-


ments over and over again based on a condition,
which is evaluated before any iterations.

String A java.lang class with methods for manipu-


lating and comparing strings.

Chapter6 Laop Structuresand Strings


Exercise 1 PrimeNumber
a) A prime number is an integer greater than 1 that is evenly divisible by only 1 and
itself. For example,2,3,5, and 7 are prime numbers,but 4,6,8, and 9 are not. Create
a PrimeNumber application that prompts the user for a number and then displays a
messageindicating whether the number is prime or not. Hint: The tsoperatorcan be
used to determine if one number is evenly divisible by another.
b) Modify the application to prompt the user for two numbers and then display the prime
numbers between those numbers.

Exercise 2 PrimeFactors
The Fundamental Theorem of Arithmetic statesthat every positive integer is the product of a set of
prime numbers. This set is called the prime factors. For example,the prime factors for 140 are 2,2,5,
andT (2*2*5*7= 140).Createa PrimeFactorsapplicationthat prompts the user for a positive integer
and then displays that integer'sprime factors.Use the following pseudocodewhen implementing the
PrimeFactorscode:
fnitialize a counter to 2
while the counter is less than or equal to the number
if the counter ilivicles the nunber evenlv
ilisplay the counter
ilivicle the
number by the counter to get a new number
else increment counter bv 1

Exercise 3 Investment
Createan Investmentapplicationthat calculateshow many years it will take for a $2,500investment
to be worth at least$5,000if compoundedannually at7.5%

Exercise 4 CarRecall
Modify the CarRecall application created in Chapter 5 Exercise4 to allow the user to input as many
model numbers as needed. Use 0 as a sentinel to end user input. The application output should look
similar to:

Enter the car's nodel nunher or E to quit = 22L


Your car is defectiue- It must b e repaired.
Enter the car's model nurnher or B to quit: 123
lour car i s n o t d e f e c t i u e -
Enten the crt'.'s model nunher or 6 to quit: ?86
Iour car is defectiue. It must b e repaired-
Enter the car's nodel numben or E to quit: E

Chapter6 Loop Structuresand Strings


Exercise 5 DigitsDisplay
Createa DigitsDisplay application that prompts the user for a non-negativeinteger and then displays
eachdigit on a separateline. Application output should look similar to:

Enter a positiue integer: ?89


?
I
I

Exercise 6 DigitsSum
Createa DigitsSum application that prompts the user for a non-negativeinteger and then displays the
sum of the digits. Application output should look similar to:

Enter a positiue integer: 892


The sum of the digits is: 19

Exercise 7 CubesSum
a) Createa CubesSumapplication that prompts the user for a non-negative integer and
then displays the sum of the cubesof the digits. Application output should look similar
to:

Enter a positiue integer= 223


The sum of the cuhes of the digits is: {3

b) Modify the application to determine what integers of two, three, and four digits are
equal to the sum of the cubesof their digits.

Exercise 8 g GuessingGame
The GuessingGameapplication createdin Chapter 5 Exercise8 would be more fun if userscould make
as many guesses'asnecessaryto guessthe secretnumber. Modify the CuessingGameapplicationas
follows:

a) Modify the algorithm to allow for as many guessesas needed.


b) Modify the flowchart basedon the algorithm modifications.
c) Modify the GuessingGamecode.Application output should look similar to:

Enter a numher betneen 1 and 2E= 2


Trg again.
Enter a numher betr+een 1 and 2E: 18
Try again.
Enter a nunber betueen 1 and 2E: 19
You uon!

Chapter6 Loop Structures


and Strings
E
d) A binary searchis a divide-and-conquertechniquefor efficiently searchinga list of
numbers that are sorted from lowest to highest.A strategythat incorporatesthe binary
searchtechnique can be used by the GuessingGame player when making guesses
about the secretnumber:

1. Guessthe number halfway between the lowest and highest numbers.


2. If the number guessedmatchesthe secretnumber, then the player wins.
3. If the number guessedis too high, then take the number guessedminus one and
make this the highest number and go back to Step 1.
4. If the number guessedis too low, then take the number guessedplus one and make
this the lowestnumber and go back to Step1.
For example,assuming 15 is the random number generatedin the Cuessing Game
application, the game would play out as follows when the player usesa divide-and-
conquertechnique:

Current Low Current High Player Types MessageDisplayed


1 50 26(i.e.,(1+50)/2=25.5) Too high.
1. 25 rs (i.e.,(1+25)/2=13) Too low.
74 25 zo (i.e.,(74+25)/2=79.5) Too high.
14 19 ro (i.e.,(14+19)/2=16.5) Too high.
14 15 14(i.e.,(74+15)/2=74.5) Too low.
15 15 r5 (i.e.,(15+15)/2=15) You guessedit!

In another program run, assuming the random number generatedis 20, the game
would play out as follows using the samedivide-and-conquer technique:

Current Low Current High Player Types MessageDisplayed


1 50 26(i.e.,(1+50)/2--25.5) Too high.
1 25 rs (i.e.,(1+25)/2=13) Too Iow.
14 25 20(i.e.,(14+25)/2=19.5) You guessedit!

When this approachis taken, it has been proven that a player will not be required
to make more than Logrn guesses,in this caseLogr50,or at most 6 guesses.Try this
technique yourself. Explain in your own words why this works. Would this strategy
be possibleif hints were not given after eachguess?

Exercise 9 PowersTable
Createa Powerslable application that displays a table of of powers similar to:

x^1 x^2 x^3 x^4 x^5


111L1
2481532
392?81243
4 16 64 256 LE24
5 25 125 625 3125
6 35 216 1296 ???6

e Chapter6 Loopstructures
andstrings
Exercise 10 GCD
Create a GCD application that prompts the user for two non-negative integers and then displays the
greatestcommon divisor (GCD) of the two numbers. The GCD is the largest integer that divides into
both numbers evenly. An algorithm for finding the GCD is called Euclid's Algorithm. Use the follow-
ing pseudocodewhen implementing the GCD code:
while (num2 > 0) {
temp=num1%num2;
numl = num2;
num2 = temn:
]
Application output should look similar to:

Enter a nurnher: 32
Enter a second nunher: 4E
The GCD is I

Exercise 11 ElapsedTimeCalculator
What comes13hours after 4 otlock? Createan ElaspsedTimeCalculator applicationthat prompts the
user for a starting hour, whether it is am or pm, and the number of elapsedhours. The application then
displaysthe time after that many hours havepassed.Application output should look similar to:

Enter the starting hour: 7


Enter an oll pn; pm
Enter the nunber of elapsed hours: 18
The tine is: S:EE an

Exercise t2 Necklace
An interestingproblem in number theory is sometimescalled the "necklaceproblem." This problem
begins with two single-digitnumbers.The next number is obtainedby adding the first two numbers
togetherand saving only the onesdigit. This processis repeateduntil the "necklace"closesby return-
ing to the original two numbers.For example,if the starting two numbersare 1 and 8, twelve stepsare
requiredto closethe necklace:1.89 7 63 9 21 3 47 1 8

Createa Necklaceapplicationihat prompts the user for two single-digitintegersand then displaysthe
sequenceand the number of stepstaken.The applicationoutput should look similar to:

Enter the finst starting nunber: 1


Enter the second staFting number'.: I
18975392134?18

Chapter6 Loop Structuresand Strings


Exercise 13 Hailstone
An interesting (yet unsolved) questionin mathematicsis called "hailstone numbers." This seriesis
produced by taking an initial integer,and if the number is even,dividing itby 2.If the number is
odd, multiply it by 3 and add 1. This processis then repeated.For example,an initial number of 10
produces:
10,5, 16,8, 4, 2, L,4, 2, 7 ...
An initial value of 23 produces:

23,70,35,106,53,160,90,40,20,10,5, 16,g, 4, 2, 7,4, 2, L, . .


Note that both numberseventuallyreachthe 4,2, I, 4,2, 1 . . . cycIe.Createtwo applications(Hailstonel
and Hailstone2) that answer the following questionsfor initial values of 1 to 200:

a) Do all integersfrom 1 to 200eventuallyreachthis cycle?


b) What is the maximum number of iterations to reach the cycle and which starting
number producesthis maximum?

Exercise L4 DiceRolls
Create a DiceRolls application that displays five rolls of two dice where each die is numbered from L
to 6. The applicationshould also show the total of eachroll:

DicelDice2 Total
61?
6418
336
358
314

Exercise 15 Chaos
"Chaos theory" is a subfield of mathematicswhich relies heavily on the computer.A simple chaos
experimentis:

Start with any real number x between 0 and 1. Generatea new number using the
"logistic equation:"
x=2*x(1 -x)

Display this new x and repeatthe process50 times.


a) Createa Chaosapplicationthat prompts the user for a starting value and then performs
this experiment.Make a prediction aboutwhat happensfor different starting values.
b) Modify the application so that the 2 in the logistic equation can be replacedwith a
value specifiedby the user in the range 2to 4,but the starting value of x is always0.5.
Note any interesting behavior.

@| Chapter6 LoopStructuresand Strings


Exercise 16 RandomWalk
In the "random walk" problem, a person is placed at the centerof a 7 meter long bridge. Each step the
person moves 1 meter either forward or backward at random.

Createa RandomWalk application that determineshow many stepsthe person will walk before taking
a step off the bridge, Have the application average50 trials, and display the averageand the greatest
number of steps.(Hint: Generatea random number between 0 and 1, with 0 meaning to go forward
and 1 meaning to go backward.)

Exercise 17 Password
Createa Passwordapplicationthat storesa secretpasswordof your choice.The Passwordapplication
shouldprompt the userfor the passwordand then display "Welcome"if the correctpasswordis typed.
If after three tries the correctpasswordhas not been entered,the message'Accessdenied." should be
displayed.Application output should look similar to:

Enter the passuord: homer,'ronk


The passuord gou typed is incorrect.
Enter'. the passurord: football
The passuord gou tgped is incorrect.
Enter the password: fish
The passr+ord gou typed is incorrect.
Access denied.

Exercise 18 Monogram
Createa Monogram application that prompts the user for his or her first name, middle name, and last
name and then displays a monogram with the first and middle initials in lowercaseand the last initial
in uppercase.Application output should look similar to:

Enter your first nane: f,lonso


Enter your niddle initial: H
Enter your last nane: f,fsy

Your monogram is: aEh

Exercise 19 RemoveString
Create a RemoveStringapplication that prompts the user for a sentenceand a string. The application
should then remove every occurrence of the string from the sentence.The application should look
similar to:

Enter a sentence: I hope you haue a really nice day.


Enter a string: reallg
I hope you haue a nice day.

Chapter6 Loop Structuresand Strings


Exercise 20 CountVowels
Create a CountVowels application that prompts the user for a string and then displays a count of the
number of vowels in the string. Application output should look similar to:

Enter text: Jaua Frogranning fissignnent


The nunben of uouels in Jaua Progranning fissignnent is I

Exercise 2I GroupAssignment
Createa GroupAssignment application that prompts the user for his or her name and then displays a
group assignment.The group assignment depends on the first letter of the student's last name. Last
namesbeginning with A through I are assignedto Group 1, J through S are assignedto Group 2, T
through Z are assignedto Group 3. Application output should look similar to:

Enter gour first nane: Janus


Enter your last name: Smith
Janus Smith is assigned to Group 2

E chapter6 Loopstructures
andstrings

You might also like