Chapter 5: Conditionals and Loops Lab Exercises
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
Election Day
34
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
Ex. 2
//******************************************************************** // 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"%&
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(%&
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?
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
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.
// *************************************************************** // 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