New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Programming I

by: Kathryn Eichmann

Programming I COP 2210

Kathryn Eichmann
GPA 3.8

Joslyn Smith

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Joslyn Smith
Class Notes
25 ?




Popular in Course

Popular in Computer Programming

This 39 page Class Notes was uploaded by Kathryn Eichmann on Monday October 12, 2015. The Class Notes belongs to COP 2210 at Florida International University taught by Joslyn Smith in Fall. Since its upload, it has received 27 views. For similar materials see /class/221728/cop-2210-florida-international-university in Computer Programming at Florida International University.

Similar to COP 2210 at FIU


Reviews for Programming I


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/12/15
Iterative Statem ent l The while Statement 7 Nested while Loop 5 The dowhile Statement 70 The for Statement 7 Nesting for I mm 77 Scope of a Loop control variable 79 m 7 9 Pitfall I 7 Updating the loop variable incorrecth 7Q Pitfall II 7 Modifving the loop variable in loop bodV 7Q Iterative Statements So far in our studies we have discussed and have been using two forms of Java statements 7 sequence and selection There is a third type of Java statement 7 the iterative statements commonly called loops Iterative statements cause a program to repeat certain statement or block of statements The statement or block of statements is referred to as the loop body You may be wondering how the program knows to execute the loop body repeatedly The answer is a conditional expression is used to determine if the loop is to continue to execute or to terminate If you were asked to add all the integers from 1 to 1000 and the only method that you know was addition you would more than likely write something like this 112 213 314 415 516 Surely it will not be long before you realize that this approach is repetitive and laborious The concept iteration which is a fundamental tool to programming relieves us from this drudgery In likewise manner the computer is capable of carrying out tasks on a repetitive basis Java provides three forms of iterative statements These are the le e statement the do Wb e statement and the far statem ent The while Statement The format of the le e statement is as follows While con dition aL eXpressjon body Where the word while is the Java keyword indicating a repetitive construct Within the pair of parentheses is a conditional expression that must be tested in order to determine if the loop body must be executed again and again until a certain condition stops it The While statement specifies that the conditional expression must be tested at the beginning of the loop If the conditional expression is initially false then the loop body is skipped Figure 414 shows a diagrammatical representation of the while loop Initialize the loop variable Loop body Usually includes updating the loop variable Program execution continues Figure 414 symbolic representation of the While loop Example 48 Write a whjle loop that prints all the integers from 1 and 1000 Solution The solution to this problem focuses on two key issues counting from 1 to 1000 and print the number The counter 1 solution is depicted in Figure 415 I Print the number I Update counteri counter counter 1 I Program execution continues I Figure 412 a diagrammatic solution t the problem Listing 415 shows the solution in code form public class In tegers public static void main String arg 1 2 3 4 int counter 1 5 While coun ter ltJ 000 6 7 8 9 System outprin tin coun ter counter counter 1 1o Listing 415 using the while loop Line 4 declares and initializes the loop variable counter It is used as the basis for the conditional expression counter lt2 1000 in the while clause See Line 5 The loop body is enclosed with the pair of curly braces Lines 7 and 8 form the loop body In example 48 we were told the number of times that the loop must iterate There are times however when we do not know the number of times that the loop will iterate In situations of the kind we will have to set up the conditional expression so that the loop must terminate Example 49 Design a class that accepts an integer value and prints the digits of the number in reverse order For example if the number is 234 the program should print 431 or if the number is 24500 it should print 00542 Analysis Based on the problem definition we cannot tell in advance the number of digits contained in a given number We must however print the digits from the rightmost to the leftmost one That is 19 Given a number say N The rightmost digit that is to be printed is determined by N 10 For example if the number is 234 then the rightmost digit to be printed is 23410 which is 4 The next rightmost digit in N is determined by N10 Using the example 234 the next rightmost digit is 23410 which is the number 23 This is N Steps 2 and 3 are repeated until the new value in N is zero For instance let N 234 then the process works this way N Process Digit printed 234 23410 4 23 23410 23 2310 3 2 2310 2 210 2 0 2 10 Listing 416 shows the class ReverseNumber It is a translation of the algorithm worked out above 1 2 3 4 90909901 public class Reverselv umber priva te in t N priva te Stn39ng 3 public ReverseNumberG39n t N tbiSJV N m A S void re verse Wb e Ngt 0 ss N9 10 NN10 public Stn39ng 05271ng return 3 Listing 416 shows how the digits in a given integer can be reversed The constructor accepts an arbitrary integer N The method reverse shown on Lines 10 17 shows the process by which the digits are reversed The while clause shows the conditional expression which governs the loop body 7 Lines 14 and 15 As long as the conditional expression is evaluate to true the loop continues to iterate The iteration stops when N becomes zero Note instead of printing the digits immediately after generating them they are appended by the string variable 5 Line 15 Listing 417 shows a typical test class that utilizes the class ReverseNumber public class TestEeverseNumber public sta tic void 127 ain SL71th arg 1quot reverse 0 1 2 3 4 5 ReversmgN umber 1quot new BeversrthumberQ4500 6 7 System outprin 117 1quot 8 9 Listing 417 Test class for the class ReverseNumber Sometimes the conditional expression stated in the problem is less intuitive than what we have seen in the previous section When such situations arise there is a high degree that two or more relational expressions are involved If you are faced with situations of this kind design a Boolean method solely to formulate and test the condition under which the loop will operate Example 410 The XYZ School wants to carry its grade 10 students on a trip The cost of the trip is 5 00000 The school has only thirty days in which to collect the funds in order to go on the trip Design a class called SchoolContribution that creates a contribution account Incorporate the following I A method called totalContribution that accepts and accumulates the daily contributions I A Boolean method called hasMoreTimeo that determines if more time is needed to reach the targeted amount I A Boolean method called hasNotMadeTarg39etO that determines if more contribution is needed A Boolean method called metTargetO that reports if target has been met Write a test class called TestContribuu39on that generates the daily contributions It keeps making contribution until it determines that either the targeted amount of contribution is met or the time allotted to collecting the amount of money expires In either case it displays the amount of money collected each day and the accumulated amount Analysis The class SchoolContribution has Constants o TARGET the amount ofmoney to be made 500000 0 MAXiDAYS number of days in which to meet target 7 30 I Variables 0 day the day that contribution is made 0 totalContribution 7 the amount collected at the close of each day I Constructor 0 The initial amount of money collected is zero I Methods 0 addContribution 7 accepts a contribution adds it to total contribution and updates the count for number of days Boolean methods hasMoreTimeO and hasNotMadeTargeto allow the loop to continue if target is not met within the 30 days That is the target is not met if the amount collected is below the targeted amount and the number of days is less than 30 The following conditional expressions represents each of the methods respectively 0 day lt MAXDAYS and totalAmount lt TARGET o Boolean method metTargetO 7 tells us if the target was met That is after 30 days was the target met This is answered by the following conditional expression day gt MAXDAYS ampamp totalContxibution lt TARGET This is less obvious but it is necessary to know in order to print the output Listing 418 shows the definition for the class SchOOIContribution 1 importja Va teXtNumberF0rma t public class SchoolContribution static final byte DA Y S 30 static final cat TARGET 5000 in t day double totalCon tIibution String s NumberForma t d SDQONQ 10 public School Con tIibu tion 0 1 1 1 2 totalCon tIibution 0 13 day 0 14 s I quotBe y tDaily Contribution tTotal Contribution n 1 5 df NumberForIn atgetCurrencylnstanceO 16 1 7 public void addCon tribution double am 0un t 18 19 totalCon tIibution totalCon tIibution am 0un t 20 dayday1 21 539 3 day quott dfformata1n0unt 22 539 3 quottt dfformatt0talContIibuti0n quotn 23 24 public boolean basNotMadeTarget 0 26 return totalContIibution lt TARGET 27 28 public boolean basMoreTimeO 30 return day ltWDA YS 32 public boolean metTarget 0 34 return day ltMAJQDA YS ampamp totalContIibution gt TARGET 36 public String toStIrngO return 3 Listing 418 the class SchoolContrlbutlon To summarize this class simply does the following I It accepts the daily amounts accumulates the contributions and updates the day count These activities are shown the method addContr39ibution I Determines the conditional expression for the loop as seen in the method didNotMakeTargetO I Determines Whether or not the target was made See the method islnadequa teO Listing 419 shows the code for the test class TestContribution The class does the following Creates an empty contribution account Continuously check if the target has been met It uses the result from the method d139dN0tMa1reTargetO to control the loop after a day s contribution has been made Prints the result after the loop is exited The if statement on Line 12 uses the result from the Boolean method is117adequa 90 to print the result 1 i177p0rtja VaXSWi17gJOpti017Pa179 2 public 01ass TestC017 Iibuti017 3 4 public Sm tic V0id 177 21117 String arg 5 1 6 S017 001 0017 tub 0 11017 s 17 e W S017 001 0017 trib 0 11017 0 7 While 539 basNotMadeTaIgeto ampamp aliasMan imeO 8 9 s addCon tn39butian DoubleparseDoubIe 10 J0pti0nPanesIzaWInputDia10gquotMaIre 1017 tn39butian 9 11 12 if 9 metTarget 0 System 0utp1i17 117 91 9139 System 0utp1i17 117 We did 1701 make 1179 target quot17S0r1y we 0a17170t g0 017 179 tnp 17 S 13 1 4 Listing 4 19 the test class TestContribution In Listing 419 the while statement monitors the loop body It calls the methods 17aSNOtMadeT argetO and basM0reTi17790 to tell if the loop must continue Nested while Loop The while statem ent like the if statement can be nested Recall that the form at of the while statem ent is while condition y Where S represents a Java statement If this is the case then S itself can be a while statement The construct would therefore be while conditionl while conditionZ S Figure 4xx shows a diagrammatic representation of one while loop that is nested Within another Initialize outer loop variable false conditionalil false 1 lnner loop body 5 Update inner loop variable Update outer loop variable V Program exits loops 10 This diagram is interpreted as follows 7 if condition 1 is true then the inner part of the diagram is executed but the execution contains another condition That is what follows conditionl represents the outer loop body This loop body constitutes condition2 If this condition is true then what follows is the inner loop body This loop repeats until condition 2 is false at which time execution returns to the outer loop The outer loop continues until conditionl is false at which time the entire loop terminates Example 4xx A company has five stores 7 A B C D and E 7 at different locations across the state of Florida At the end of each week the company s management prints a report of the daily sales and the total sales for each of the stores Write a class called Sales that prints the sales and the total sales for each of the stores row by row 1 impcrtja VaXSWJngJOpti0nPane 2 impcrtja Va teXtlu1nberF0r1na t 3 public class Sales 4 5 pIiVate double totalSales 6 pIiVate static finalint DAYS 7 7 pIiVate static final cbar STORES E 8 pIiVate String beader 9 pIiVate String s 10 pIiVate static final 39umbm IL mat nf 39umberE netV Kl 1 1 public SalesO 12 1 3 totalSales 0 14 s quot quot 15 header St0retttl7ayn 16 quottt2t3t4t5t6t7tT0taln 17 18 public void getSalesO 19 20 char store 24 21 While store lt STORES 22 23 s s st0re 24 int dayZJ 25 totalSales 0 26 While day ltDAYS 27 28 double am cun t Z Double parseDOubl 9 J Op ticnPan e schlnputDial 0g quotStore st0re nDa y day quotnEn ter amountW 29 s s quott nfff0r1nata1n0unt 30 dayJH 31 totalSales totalSales am cun t as 5 e 5 quotw nfformst otalsales quotn z 34 starevwn 35 J a 7 pubzre Stung msmnga 39 return header 4 s 1 ImportWax swlrg JOptnmPane 2 ImportWax 5w 3 ImportWax swlrg erArea 4 5 pubzre as 55 T95 53195 5 7 pubzre 559 no me mam sunny su g a 9 Sales 5 new Se1es a 5 579593195 1 o 11 JTeXtAJ eS c new JTextAreae toStrJngO a 50 1 2 JScraHPsI e upene 1 a JOptIonPaI e 5 owMessegeDrezogm u11 p quotWeekly Se1es 1 JOonnPSIe INFORI JA TIGALMESSA GE 1 4 A 1 5 Cancel H 31qu DaWSa es mznann mznnnn mzaann man suaann Tma sz ao m mznnnn 11 UU55U suannn 3155 nu Wyannn sw n nnn sz nnnnn smegma umsn suennn sumac su nnn u nnnnn szn amnn As we have seen there are problems that require nested looping construct in their solution However some of those problems do not explicitly say so nor do they make any indication of the use of a loop It is therefore left to the experience of the programmer to recognize that looping construct is required what the conditional expression for the loop will be and how it will be implemented Example 412 Write a program that makes mailing labels Assume that the information is gathered line by line That is given the name and address as one line of text the program should write the name of the person on the first line the street on the second line city on the third line and so on For example given the line of informationi John Brown 3300 Spanish Moss Terrace Apt 240 Lauderhill Fl 33319 The program should output John Brown 3500 Spanish Moss Terrace Apt 240 Lauderh l F1 333 19 In this problem we want to design a class that basically does the following I Accepts a string value I Decomposes or parses the string into separate units Each unit is commonly called a token I Extracts each token and prints each on a separate line In order to decompose a string into tokens Java provides a class called String l okenizer for this purpose Two of its most frequently used constructors are I String l okenizerStIing s This constructor parses a string into tokes by using default delimiters These default delimiters are the space character the tab character the new line character the carriagereturn character and the formfeed character I String l okenizerString 5 String delimiter This constructor parse a string according to the delimiter specified The delimiter itself is not part of any of the tokens The second constructor is more applicable in this problem because we can use the comma character as the delimiter between tokens Three of the more frequently used methods in this class are boolean hasMoreTokenso This method tests if there are more tokens available in the string I String nextTokenO This method returns the next available token from the string String nextTokenString delimiter This method uses the argument given to set a new default delimiter It then returns the next available token I countTokensO This method returns a count of the number of tokens in the string The class StringTokenizer is found in the javautil package It must be imported Now that we have the requisite tools we can move on to solving the problem Let us do the following 1 Name the class that makes the mailing labels MailingLabels 2 Define a method called makeLabels that accepts string values one at a time and tokenizes each Figure 413 shows how the method will loop through a tokenized string to get the next available token Listing 420 shows the code for the class MailingLabels Tokenize string Get nextTokenO and process it v Next statement I Figure 413 shows how the while loop will be used to get a get a token Listing 420 implements the flow diagram shown in Figure 413 1 impart java util StringTokenizer 2 public class Maz ugLabels 3 4 Stung s 5 MaJZI39ngLabeIsO S W 6 void makeLabeISGStzmg SET 7 8 String taken quot 339 9 StringTakem zer t new StzingTokeniztzr tr 139 10 While thasMareToIrensO 1 1 12 token tnextTaken 0 1 3 taken taken trim 0 14 sst01ren n 39 1 5 16 ss n11 17 f 18 public Stung L OSL H39HgO return 3 19 Listing 420 the code for the class MailingLabels The focus in this class is how the While construct makes use of the StringTokenizer class First of all in order to use the StringTokenizer class it has to be imported as seen in Listing 420 Line 1 The method makeLabels is the next key issue This class accepts a string value See the method header Line 6 Line 9 thru Line 16 is a translation of Figure 413 First the string is tokenized using the comma as the delimiter See Line 9 Next the Boolean method basMaIeTokensO checks to see if there is another token in the tokenized string See Line 10 If there is another token it processes it39 if there is no more then the loop body is skipped and control passes to Line 16 Also notice the loop body Line 12 fetches the next available token39 Line 13 trims any blank that may be to the left or to the right of the string and Line 14 simply concatenates this new token and the new line character to the existing output strmg 3 Listing 421 show a typical test class for the class MailingLabels 1 Importja VaXSWJ39ng JOp tl39onPan e 2 public class TestMaIImgLabels 3 4 public static void main String arg 5 6 Algi39lincrf aka m neW Algi39li39ncrf 2kg 0 7 Stirrth J Opt1390nPanesI10anputDjalog En tername and address 8 While Csequals 9 10 mmakeLabels939 1 1 9 J0pt139anPanestWInputDiaJogWEnter name and address 12 1 3 System outpn39n 111 111 14 15 Listing 421 test class TestMailingLabeIs The focus in this class is the use of the while loop again Because we do not know in advance how many mailing labels there will be we use the while loop to determine this That is the loop will continue to execute as long as the JOptionPane does not return a blank string See Line 8 in Listing 421 Still there are other types of problems that give some indications of iteration through formulae or through patterns Problems that fall in this category usually require some Mathematical skills and analytical skills to solve them Example 413 The value of 11 can be determined by the series equation n41 1315 1719 111113 Write a class called PI that finds an approximation to the value of 11 to 8 decimal places Write a test class called TestPI that displays the value of 11 and the number of iterations used to find this approximation Analysis Each term is the series is generated as follows x13912 1 1 X2 1221 x3391231 In general the ith term is X 391i2i 1 This type of problem requires you to compare the absolute value of the difference of two successive terms If the value is less that the threshold or margin of error then the new value generated is the approximation to the actual value In other words while Ixnew 7 xoldl gt some margin of error sum the new value to previous amount save the new as old generate the new value xnew In this example the margin of error is 000000005 In addition each new term may be generated as follows expression X Matbp0wJ0 nl2 1 1 Listing 422 shows the class PI 1 2 3 4 5 6 7 importja Va teXt NumberForm a t importja Va teXt Decim achrm a t public class P static final double 114A GlNi OKEREOE 100000005 double sum in t itera te public P10 sum 1 public double fin aneWG39n t 17 return Mathpow l nl2 1 1 p ublic void fin dPiO in t i 1 double Xold 10 double XneW thnewG While Walthabs mew xaId gt1M4EGIIV OFLERROR sum sum XneW X01d xneW jH XIzeW 39naner9139 24 25 iterate i 26 27 public String toStIingO 28 29 NumberFormat 17f NumberFormatgetfnstanceO 30 DecimalFormat df Decim aIFormatnf 3 1 df appIyPa ttern quot0 00000000 32 return quotThe approximate value of pi is dfforma 4 sum quotn quotThe number Ofitera tions is itera te 33 34 Listing 422 the class PI The test class shown in Listing 423 simply creates a PI object calls the method findPi and then prints the result 1 public class TestP 2 3 public static void main String arg 4 5 Pip IneWPIO 6 pfindPiO 7 System outhin tln p 8 9 Listing 423 the test class TestPI Exercises 4c 1 Study the following programs and write down what will appear on the screen you compile and execute them a public class Mystr39y public static void mainString arg int k 1 while k lt 10 Systemoutprintlnk ki b public class Mystry public static void mainSt1ing arg int k 2 while 27k lt 6 Systemoutprintlnk 27k k c public class Mystry public static void mainSt1ing arg int In 2 n 50 while m lt n mn3 Systemoutprintlnm ll 01 public class DoubleLoop public static void mainString arg int i 4 while i gt 1 Systemoutprinti int j 3 while j gt 1 Systemoutprintln t j j39 39 Syseem mcpmunt 1 J 2 Wm a class cz cd TestSnnrzs Fm my ngn mm hz mm m n 0 Wm 1 mm cz cd addsme m Mccp hz m at mh mm nduzl mi mm m Aka m a mum cz cd avugm Scme Giannini1m m1 mmm hzavemge m rmmmm Wm am this mllni TestSnmes m this use hz JOphnnPanE mam Wm m madth m m m nme mpmsems ti mmmcm t39nrezchsmdcm ms 1 fdlnwedhy hz zamhcmes 3 Wm a class cz cd Numhm m rm ti mmmm m sequerce n1ngth nudier 11 2125315 3mm t when m by m Wm mm mllni ndemmum m Mm hz mme hz 1m mm mm mm mm ml mdenhm hywem mm lammhemfenmzi m1 hz mmmmm ti 1mm sequent m m hummus ti pm mm mm anmmm hmgemtni hz mm thnanqgahve mmm maxi mm amps mi hz med Fnrexzmplzgmmhz fnllmurg mm m 250 450 50 m 1m 75 7mm pmgmm 5mm gamma m mpm mm m hz numg a mallest number i 5nu 4 MnMyExemm tummyth mm mm ti ms m h sequent mpmgmsmm gamma mumw ti rnuwm The largest number 5 Wntaalavapmgnm hmcanheuiedm 9mm 1mm WEAng m The Mwhrls Smemenl m helmphndy m fnmmm39 39e m wmmtammmn a statement pm madman mm mm nmdmnml Expressmn 21 Figure 413 a symbolic representation of the do WhiIe loop Figure 413 is representing the construct of the dowhile loop The d0while loop must be used with caution since it is attempting to execute the loop body without knowing if it is possible For instance consider the following segment of code in t i 1 do System 0utpIiu tlu 16 391 leIle i 0 Although the code is syntactically correct it fails to execute You may ask why it did not execute when there is a conditional expression that should take care of the error Line 4 indeed carried out the test for division by zero but this test comes too late the division in Line 4 has been attempted already In general it is not guaranteed that the execution of the loop body will ever be completed at all upon a first attempt at executing it If you intend to use this looping construct your code should guarantee that execution of the loop body will terminate norm ally The following program segment creates a string and then uses the dowhile loop to print each character in the string iuti 0 Strings new StringC39Helloquot do System 0utpIiu tlu 9 ch arAtG39D i i 1 Wlulei lt sleugtb 0 This code by itself works fine However let us construct a class called DoWhile that incorporates this segment of code in a method called doFirstO The class definition is shown in Listing 424 1 public class Do While 2 3 pIiVate S tIiug s 4 public Do Wbil e S tIiug s 5 6 tbiss s 7 8 public void dOFirstO 9 22 1 0 In t 139 0 1 1 do 12 2 13 System outpzm n charAtw 14 j 1 1quot 1 5 39W121 Ie 39 ltsIengtb 0 16 17 Listing 424 use of the do while statement to print the individual characters of the string As we said before if you intend to use the doWILiIe statement you must ensure that the loop body will execute without flaw In Listing 424 the program fails if the class gets an empty string That is the clause scbarAtd fails because charAtm would not have existed This problem is fixed by checking if the string is empty This can be done in one of two ways namely check 1 lsequals or 2 slengtho gt 0 The for Statement The for statement like the WhiIe and the doWIz e statements is a looping construct that continually executes a section of code if a given condition is true When the condition becomes false the section of code is skipped and the next statement following it is executed The general format of the for statement is as follows for da tag type Id 13917139t139a1 Value con dition aL eXpressjon adjustijd sta fem en ts The for loop is a single executable statement consisting of two major parts 7 loop heading following the keyword for and the loop body The loop heading is enclosed within the pair of parentheses and consists of three parts each separated from the other by a semicolon I The first expression da tag type Id 13917139t139a1 constitutes the declaration and initialization of the control variable for the loop I The second expression condz39tjonali eXpressz39On constitutes the condition under which the loop iterates Any valid conditional expression is acceptable I The third expression adjustijdi updates the value of the loop variable 23 The loop body constitutes the statement or statement block to be executed The loop body executes only if the conditional expression is true other than that the forloop terminates Figure 414 shows a diagram of the forloop dataitype I Figure 413 a representation 0 e 0139 00p The forstatement behaves the following way 1 First the control loop variable is declared and initialized 2 Second the condition is tested If the condition is true the loop body is executed if not it terminates 3 Third the loop variable is updated That is the control variable is reassigned and step 2 is repeated Example 412 Write a program that lists the integers from 1 to 10 along with their squares and their cubes That is the program producesi 1 1 1 2 4 8 3 9 27 Let us represent the solution using a ow diagram as shown in Figure 414 Print N NN NNN I iH I F39glmtldjav 1m maxim Lining A5 51mm Wmmrigmm 1 publiulasspowels 2 3 publu spam voidinngth 31g 4 5 System outpuntldw w39mmvm 5 Gar 39icl quot Magma quott39 i 39u39u 7 B Lim39lgt uxingdnjavluq unnmul m pmblemfnclms my use nf l lz n l np ng Line 5mm 5 Bags m mm 1mng 15 mamadbm clam m 1 1 m mum m1 hz mummy 15 mamadbm clam w m m Innpbudyls mmdby System nutpnntln1 t 1 1 t 1 1 1y Fm w 511mm man an tn continue Figmw MN mn 25 Example 413 Write a class that accepts a string value and places a pound sign 9 character between successive letters For example given the word ASSIGNMENT the program would print ASSIGNMENT as the output S olution I Let us call the class Word I Principal variable is the string variable containing the value I Principal method must address the following a The number of characters in the string This can be determined by the method lengthO from the class String b V Declare and initial the index variable say i In this case it begins at 0 since the index of a string begins at 0 That is this clause takes the form inti 0 c The conditional expression that controls the loop In this case the index variable say i lt lengtho d Update the loop variable In this case iH e Define a new string variable such that after each character is encountered a pound sign is placed to the right of that character in the string except for the last character Listing 426 shows the code for this problem 1 public class Word 2 3 private String a Word 4 private int indeX 5 public W0rdStnng s 6 7 a Word s 8 index s19ngtb0 9 10 public String toStIingO 1 1 12 Strings quot 0 13 for ntj 0391 ltz39ndex1 I 14 15 9 5 a WozdcbarAt Z 16 if 39 findeX 1 17 9 5 quotJ 18 19 return 3 26 21 Listing 426 using the for loop to traverse a string In Listing 426 focus centers around the for loop construct in the toStr39ingO method Although the problem did not suggest in any way looping when we analyzed the problem we discovered that it was necessary to access each character in the string serially Furthermore we knew the position of the first and last position in the string This makes for easy traversal of the string using the forloop seen in Line 13 The test class Listing 427simply creates a Word object with the string ASSIGNMENT 1 public class Test Word 2 3 public static void main String arg 4 5 Word W new WordWASSlGNlMENT 6 System 0utp1iu tln W 7 8 Listing 427 class TestWord Example 414 A palindrome is a set of data values that is identical to its reverse For example the word MADAM is a palindrome the number 123454321 is a palindrome likewise aaabbaaaabbaaa Design a class called Palindrome that accepts a string and determines if the string is a palindrome To determine if a sequence of characters is a palindrome do the following I Compare the first and last character in the sequence If the are the same I Compare the second character and the second to the last character in the sequence I Continue the process in similar manner If all items match then the string is a palindrome I Conversely at the first mismatch occurrence then the string is not a palindrome 1 public class Palindrome 2 3 pIiVate String word 4 pIiVate boolean palindrome 5 pIiVate int index bal udeX p ublic Palin dram e Stung s word s in deX slengtb 0 999099 27 10 palindrome true 1 1 hal ndeX indeX2 12 1 3 boolean isPalin dram 90 14 15 for int i 0139 ltI7a1 ndeX ampamp palindrome14 16 ifW0rdcharAt39 wordcharAthdeX 39i 39 1 1 7 palindrome Zfalse 18 return palindrom e 19 20 Listing 427 class Palindrome accepts the string and check if it is a palindrome In Listing 427 we assume that the string is a palindrome by using the Boolean variable palindrome true See Line 10 Instead of traversing the entire string in one direction we half the index so that we can compare values at the corresponding ends as described above If any two characters at corresponding ends are not the same then the variable palindrome is set to false and the forloop terminates As we said earlier the conditional expression in a for loop can be any valid Boolean expression For instance the conditional expression for this for loop is a logical expression i ltIzal ndeX ampamppalindmme The test class Listing 428 creates a Palindrome object with the string aaabbaaaabbaaa 1 public class TestPaZin drome 2 3 public sta tic void main SL71th arg 4 5 P quot p Inewf m ilm l Jun1 6 System outprin 117 nisPaIin dram 902 7 8 Listing 428 Test class TestPalindrome Nesting for Loops The far loop may be nested The depth of nesting will depend on the application Let s say we want to write a class that prints the twelve times table or any of the tables we could use two for loops for this purpose Example 415 Desxgn a class umpnms any ummble 1 1 2 3 4 5 s 7 s 7 1 2 WM 3 4 publtr stab vutd mam Stung azg 5 l 5 System out p1mt1nquotEntel numbal 0 am am quotI 7 Spams Bad Smnnal mate System m 8 thIIEadnaXtInt 9 smngs quotn xquot 10 011nm 11 ltN 1l 11 ssquottquott 12 5 5 quotnquot 13 fat 1n k1klt12k1 14 l 15 19 1s limm 1 N 17 5 quotm Md L 18 quotnquot 19 1 20 System uuzpuntlnlgl 29 Scope of a Loop control variable In general the loop control variable must be must be declared before it is used in the loop The scope of this variable will be in the program block in which it is declared However it is advisable that this variable does not extend beyond the header of the for loop If it is extended beyond the header the program could suffer from serious side effects such as the variable picking up values outside the limiting value of the conditional expression The loop control variable can be used inside the loop body just like any other variable However the variable should not be modified by the loop body This too can cause serious side effects PitFall It is absolutely essential that a for loop be written in such a way that the conditional expression will eventually evaluate to false If not the for loop will never terminate this is called an in nite loop If your program appears to hang check the farloop to make sure this didn39t occur Here is an example Pitfall I Updating the loop variable incorrectly public class PitFallil public static void main String arg for int i 10139 gt 1 14 Systemoutpn39ntln quotThe Value of i is i WNQP PPON N Pitfall II Modifying the loop variable in loop body The control variable is local to the for statement It is recommended that you do not change the value of the loop control variable within the body of the for statement To do so could cause the program to produce incorrect results public class PitFallill public static void main String arg for int i 1 i lt 1014 53915909 Systim an t pun HI 2 1 1 1 5 wmd 10 11 Exercises 4d dLlAA m Hintruse furluups Fm example Lheletta L was farm by the nude m the methud makeLO publm class Latte 31 static String s quotquot static String makeLO s quotn for int i 1 i lt 10 i s s quot11 quotnquot for int k 1 k lt 7 k S H s s nquot for int k 1 k lt 7 k s s quot11 return s nquot Note 7 you will need a test class to run this class 32 Summary I The statements in a program will execute in a linear fashion unless they are directed otherwise I The control structures called selection and iteration are used to alter the order in which statements are executed I The selection construct has two forms namely the if statement and the switch statement I The if statement simply determines if a statement or statement block must be executed The decision is based on the outcome of a Boolean expression I The ifelse statement determines what statement must be executed from a series of choices I The if and ifelse statements may be nested I The switch statement is a special form of the ifelse statement I The switch statement can only test byte short int and char data types I The case labels must be unique They cannot be represented by variables They must either be literals or they may be represented by constants I The default statement is optional I Iterative statements 7 while dowhjle and for 7 cause a program to repeat certain sections of programs called the loop body I A loop body whether a single statement or a block of statements gets repeated based on some conditional expression I The while statement specifies the conditional expression before the loop body is specified If the conditional expression is false initially then the loop body is skipped If it is false after the loop body has been entered then the loop is not repeated again but is terminated I The dowhile statement specifies the conditional expression after the loop body 7 hopefully 7 has been executed 33 Exercises A wholesale company discounts the price of its products depending on the number of units bought and the unit price per for each item The rules for calculating discounts are shown in the table below To solve this problem do the following i Use the class GetData from assignment 4 to read the data from the keyboard Write a class called Discount that accepts the number of units and the corresponding price It validates the quantities and calculates the discount amount where possible Redefine the method t0String to form at the output NOTE DO NOT USE ANY LOGICAL OPERATIONS IN THIS EXERCISE iii Write a test class called TestDiscount that uses the data given below to test class Discount iv Write a class called Report that accepts a string object The class simply displays the result in a scrolling JOptionPane window Use the following test data Quantity Unit Price 10 1500 10 500 50 1000 200 2500 80 5000 10 2000 The output must be of the form The quantity is xx The unit price is xxxx The discount is xxxx Or The quantity is xx Quantity is negative Cannot compute discount Or The quantity is 150 The unit price is 1500 The money is negative cannot compute discount amount 34 2 The Fast Freight Shipping Co charges the following rate for shipping customer39s package Weight of Package in Kilograms Rate 2 Kgor less 110 Over 2 Kg but no more than 6 Kg 220 Over 6 Kg but no more than 10 Kg 370 Over 10 Kg but no more than 20 Kg 480 20 Kg or more cannot be accommodated 3 After a year in the business the company modifies its charges on sending packages In addition to the rules above the company charges not only by weight but also by distance It does not ship packages at distance less than 10 miles nor does it ship package over 3000 miles The rate table now reads Weight of Package in Kilograms Rate Per 500 Miles Shipped 2Kg0rless 110 Over 2 Kg but no more than 6 Kg 220 Over 6 Kg but no more than 10 Kg 370 Over 10 Kg but no more than 20 Kg 480 20 Kg or more cannot be accommodated Write a class called Freight that will determine the charges per customer The class must consider the following whether the package is over weight or not 1 Given the following code class TheSwitch public static void mainString llarg for chari 39a39 i lt 39d39 i switchi defaulti Systemoutprintlnquotdefaultquoti break case 39b391 case39aT Systemoutprinti quot quot break What will happen if you attempt to compile and execute the code a The code will not compile because the default statement should come last 35 b The code will compile because character type cannot be used for a loop variable c The code will compile and print the following on one line a b default d The code will not compile since the for statement does not have a pair of curly braces 2 Write a class called SalaryCalculator which computes the weekly salary for an employee The class E 1 accepts the name of the employee and the number of hours worked The employee gets 750 per hour for the first forty hours and 1125 per hour for each additional hour In addition the salary can only be calculated if the number of hours is between 0 and 80 Write a class called TestSalaryCalculator Use the following data to test your program John 40 Harry 85 Mary 65 James 40 Write a class called convertTemperature that can be used to convert temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius In this class the constructor accepts a value representing a temperature Provide methods to carry out the conversions Use the JOptionPane class to write a menu driven test class First the JOptionPane to enter the number that you want to convert Secondly use the JOptionPane again to select the method you want to call Use the switch statement to determine which one of the methods is to be called Here is the format of the menu Converting Temperature 1 Celsius to Centigrade 2 Centigrade to Celsius 3 Quit Use the following data to test your program 45 Celsius to Fahrenheit 100 Fahrenheit to Celsius This exercise will involve using modulus operation integer division use of the switch statement and the if ifelse statements The sign at a popular parking lot is as follows Popular Parking Lot Carsi First 1h0urs Free The next 5 hours 150hour The next 5 hours 125hour Over 11 hours Flat fee of 2000 36 Trucksi First 1 hour Free Up to the next 5 hours 175hour Up to the next 5 hours 150hour Over 11 hours Flat fee of 2500 Senior citizens in any case are charged a at fee of 250 To solve this problem do the following i Use the class called GetData to read the data from the keyboard ii Write a class called Parking that accepts as input a single character designator C T or S which may be upper case or lower case followed by the number of minutes a vehicle has been in the lot The class computes the appropriate charge for each customer Any fractional part of an hour must be counted as a full hour iii Write a class called Report that outputs the ticket for each custom er iv Write a driver class called TestParking that uses the data given below to test class Parking Test Data C 45 C 125 T 35 S 65 T 950 Use the character designator in a switch statement to determine the vehicle type The output must be of the form for each customer Popular Parking Vehicle Minutes Hours Minutes Hours Rounded Cost xxxx xx x xx x xxx Example Popular Parking Vehicle Minutes Hours Minutes Hours Rounded Cost Truck 950 15 50 16 2500 Gwen than 7 Km zx 2m Usethxsmmhudlu ndunemulufxlu a decimal places Test yuur cudewx39ha mm and mammal guess 2 Thevalue eme Expunmual cunmnt e an be damned by me Maclaunn senes a 15 51 51 x Whenxlweget n Whenxlweget wme a class mued ExpnnzmjalCnnsvzmtu esumate e m a denmal places wme a test class called Tm Expnnzmjalcnnsvzm that msplays The wine er e and me numba39 er nemuens used m nd Lhs appmxlmauun me luwest mghesl and avenge wmd speedmmngs mglqesl and axlng mmngs The test class slaps reading wines mm The keybuard when a negzuve is amazed and men pnms me manned mamgs me mgqu reading The luwest reading The number er be averaged neither The J OphunPane mpul main g wuuld repaledly msplay Lhs funnel fur mpm um 9399 Enter wind S eed reading e 2e Typxml uulpulxsas fulluws mu Hughes sneee 1s mu anest snee 1nn Number rezemus a the average rezemu 25n 11110 e 111 m1 1mg 6 dc1ec1whzn1n mpmzdmg values 7 We a cue E11101 depxs39n un m cnmpme 111g dcpmcmmn schzduks er en 2521 Use 111 m nannth me hn Tlnnn39gh linedcpnecmhnnmz m m1 Tlnmln r Ii 9quot 15111611 nfdepmcuhnn m3 yzms Fnrexzmple 111g fn nwmg um 51m 111 dcpmcuhnnmdbnnkvzluc 1111 2551 YEAR DEPRECIATION DEPRECIATION ACCuMuLATED ASSET RATE CIATION VALUE 1 13 33 33 3 66 67 2 13 33333 6 667 33333 3 13 333 33 1000 00 000 m sumrn hrdsg svmrkzs fn nws Ewe 1161mm massetnfnngmzlvzluc 1000 00 tube dcpmcmed m3 yzms Fm example 111 fn nwmg um 516w 1115 06mm Hummus 1111 YEAR DERRECIATION DEPRECIATION ACCuMuLA A RATE E ATION VALUE 1 36 500 500 500 2 26 33333 833 33 166 67 3 16 16667 10000 lerpmgmm mm have 111 fn nwug 11mm 11m dad1y 1115161166 mm whzncnllzd 1 r SW11 L111 27 Swarm ngns 39 0 7 Quit I displayHeader displays the table39s headers I straightLine displays the straight line method table with appropriate values based on the given asset I sumOiDigits displays the sumofdigits method table with appropriate values based on the given asset Write a driver class called TestDepreciation Use the following data to test the class depreciation Test your program with the following set of data I Amount 100000 years 10 method straight line I Amount 200000 years 10 method sum of digits


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.