0% found this document useful (0 votes)
115 views

Chapter 5: Conditionals and Loops Lab Exercises

Java worksheet

Uploaded by

DKz
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Chapter 5: Conditionals and Loops Lab Exercises

Java worksheet

Uploaded by

DKz
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 8

CS11R/COMP1160 Lab Exercises 6 Chapter 5: Conditionals and Loops Lab Exercises

Topics The if statement and loops Files and Exceptions Lab Exercises A Charge Account Statement A Charge Account Statement Revised

The while statement

Election Day

34

Ex. 1 Computing A Raise


File Salary.java contains most of a program that takes as input an employee's salary and a rating of the employee's performance and computes the raise for the employee. The performance rating here is being entered as a Stringthe three possible ratings are "Excellent", " ood", and "!oor". "n employee #ho is rated excellent #ill recei$e a %& raise, one rated good #ill recei$e a '& raise, and one rated poor #ill recei$e a (.)& raise. "dd the if... else... statements to program Salary to make it run as described abo$e. *ote that you #ill ha$e to use the equals method of the String class +not the relational operator ,,- to compare t#o strings +see Section ).., /omparing 0ata-.
// *************************************************************** // Salary.java // // Computes the amount of a raise and the new // salary for an employee. The current salary // and a performance rating (a String: " !cellent"" // "#ood" or "$oor"% are input. // *************************************************************** import java.util.Scanner& import java.te!t.'um(er)ormat& pu(lic class Salary * pu(lic static void main (String+, args% * dou(le currentSalary& // employee-s current salary dou(le raise& // amount of the raise dou(le newSalary& // new salary for the employee String rating& // performance rating Scanner scan . new Scanner(System.in%& System.out.print (" nter the current salary: "%& currentSalary . scan.ne!t/ou(le(%& System.out.print (" nter the performance rating ( !cellent" #ood" or $oor%: "%& rating . scan.ne!t(%& // Compute the raise using if ... newSalary . currentSalary 0 raise& // $rint the results 'um(er)ormat money . 'um(er)ormat.getCurrency1nstance(%& System.out.println(%& System.out.println("Current Salary: " 0 money.format(currentSalary%%& System.out.println("2mount of your raise: " 0 money.format(raise%%& System.out.println("3our new salary: " 0 money.format(newSalary%%& System.out.println(%& 4 4

35

Next, modify the program so that if the salary is zero or negative, it prints an error message and asks the user to re-enter the salary, and keeps doing this until the salary is positive. Also modify the program so that if the user does not input a rating of "Excellent", " ood", or "!oor", it aks the user to re1enter the rating, and keeps doing this until the rating is valid. 2hat happens if you input a string $alue such as "abc" instead of a number for salary in the program abo$e3 "dd a try1catch statement to fix this problem. 4f the user input a string for salary, print an error message. 5ther#ise, the program should do the normal computations and output that it #as doing before. The simplest format of a try1catch is
try * // code that might cause a run5time error 4 catch ( !ception e% * // statements to e!ecute if an error occurs 4

2006 Pearson Education


36

Ex. 2

riting an! Rea!ing "i#es

//******************************************************************** // Test/ata.java 2uthor: 6ewis/6oftus" modified (y 2.#. 7amilton5Taylor // /emonstrates 1/8 e!ceptions and the use of a character file // output stream. //******************************************************************** import java.util.*& import java.io.*& pu(lic class Test/ata * //55555555555555555555555555555555555555555555555555555555555555555 // Creates a file of test data that consists of ten lines each // containing integer values input (y the user. //55555555555555555555555555555555555555555555555555555555555555555 pu(lic static void main (String+, args% * final int 92: . ;<& int value& String file'ame . "test)ile.t!t"& Scanner scan . new Scanner (System.in%& try * $rint=riter out)ile . new $rint=riter (new )ile=riter (file'ame%%& for (int i.;& i>.;<& i00% * System.out.print (" nter value ?" 0i0 ": "%& value . scan.ne!t1nt(%& out)ile.print (value 0 "@t"%& 4 out)ile.println(%& out)ile.close(%& System.out.println ("8utput file has (een created: " 0 file'ame%& 4 catch ( !ception e% * System.out.println(" rror 8pening )ile: "%& System.out.println(e%& 4 4 4

Run the TestData example above. Look at what is in the text file (the text file will be inside the current blueJ project folder). Run the program again and input different data. Look at what is in the text file. Modify the program so that it asks the user for the name of the file. 1. Write a program that reads the values from the file and prints them on the screen. To read from a text file, use the following
try * // other code String file'ame& // assign or read file name Scanner scan)ile . new Scanner(file'ame%& // other code to read from scanner normally" // e.g. String s . scan)ile.ne!t(%& rror 9essage when file could not (e opened"%&

4 catch ( !ception e% * System.out.println("3our 4 37

A PrintWriter can append to a file instaid of overwriting it by opening the file in append mode, e.g.
$rint=riter pw . new $rint=riter(new )ile=riter("data.t!t"" true%%& pw.println(someting%& // will then add at the end of the file pw.close(%&

2. Change the $rint=riter creation in the TestData example above to

$rint=riter out)ile . new $rint=riter (new )ile=riter (file" true%%&

Run the program again and input different data. Look at what is in the text file. What is the difference with this $rint=riter change?

2006 Pearson Education


38

Ex. $% A Charge Account Statement


Write a program to prepare the monthly charge account statement for a customer of CS CARD International, a credit card company. The program should take as input the acountnumber, the previous balance on the account, and (as one input) the total amount of additional charges during the month. The program should then compute the interest for the month, the total new balance (the previous balance plus additional charges plus interest), and the minimum payment due. Assume the interest is 0 if the previous balance was 0 but if the previous balance was greater than 0 the interest is 2% of the total owed (previous balance plus additional charges). Assume the minimum payment is as follows: new (alance for a new (alance less than AB< AB<.<< for a new (alance (etween AB< and AC<< (inclusive% D<E of the new (alance for a new (alance over AC<< So if the new balance is $38.00 then the person must pay the whole $38.00; if the balance is $128 then the person must pay $50; if the balance is $350 the minimum payment is $70 (20% of 350). The program should print the charge account statement in the format below. Print the actual dollar amounts in each place using currency format from the NumberFormat classsee Listing 3.4 of the text for an example that uses this class. CS C2F/ 1nternational Statement .................................... 2ccount?: $revious Galance: 2dditional Charges: 1nterest: 'ew Galance: 9inimum $ayment: A A A A A

Next, modify the program so that after printing the statement, it asks if the user wants to process another account. If the reponse is y, it repeats the entire process (get inputs, compute, print statement). Finally, modify the program so that it writes the results to a text file as well as to the screen. Ask the user for the name of the file. See the example in Ex. 2.

39

Ex. 4: Election Day


It's almost election day and the election officials need a program to help tally election results. There are two candidates for officePolly Tichen and Ernest Orator. The program's job is to take as input the number of votes each candidate received in each voting precinct and find the total number of votes for each. The program should print out the final tally for each candidateboth the total number of votes each received and the percent of votes each received. Clearly a loop is needed. Each iteration of the loop is responsible for reading in the votes from a single precinct and updating the tallies. A skeleton of the program is in the file Election.java. Open a copy of the program in your text editor and do the following.

1. Add the code to control the loop. You may use either a while loop or a do...while loop (use a while if you do not know how to use a dowhile). The loop must be controlled by asking the user whether or not there are more precincts to report (that is, more precincts whose votes need to be added in). The user should answer with the character y or n though your program should also allow uppercase repsonses. The variable response (type String) has already been declared. 2. Add the code to read in the votes for each candidate (e.g. input votes for , input votes for ). Note that variables have already been declared for you to use. Compute the total votes while reading the data. Print out the totals and the percentages after the loop. 3. Test your program to make sure it is correctly tallying the votes and finding the percentages AND that the loop control is correct (it goes when it should and stops when it should). 4. The election officials want more information. They want to know how many precincts each candidate carried (won). Add code to compute and print this. You need three new variables: one to count the number of precincts won by Polly, one to count the number won by Ernest, and one to count the number of ties. Test your program after adding this code.

2006 Pearson Education


40

// *************************************************************** // lection.java // // This file contains a program that tallies the results of // an election. 1t reads in the num(er of votes for each of // two candidates in each of several precincts. 1t determines // the total num(er of votes received (y each candidate" the // percent of votes received (y each candidate" the num(er of // precincts each candidate carries" and the // ma!imum winning margin in a precinct. // ************************************************************** import java.util.Scanner& pu(lic class lection * pu(lic static void main * int votes)or$olly& // int votes)or rnest& // int total$olly& // int total rnest& // String response& // Huestion

(String+, args% num(er of votes for $olly in each precinct num(er of votes for rnest in each precinct running total of votes for $olly running total of votes for rnest answer (y or n% to the "more precincts"

Scanner scan . new Scanner(System.in%& System.out.println (%& System.out.println (" lection /ay Iote Counting $rogram"%& System.out.println (%& // 1nitialiJations // 6oop to "process" the votes in each precinct // $rint out the results 4 4

41

You might also like