Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Laboratory 7 Lesson 7-2 Exercise 1 Exercise 2 Exercise 3 Exercise 4 Lesson 7-3 Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5 Lesson 7-4 Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5 Exercise 6 Exercise 7 Lesson 7-5 Exercise 1 Exercise 2 Exercise 3 Exercise 4 Solutions Lesson 7-2 Exercise 1: The following is a sample program for Exercises 1 and 2. // Application Switches demonstrates the use of the Switch // statement. import java.util.Scanner; public class Switches { public static void main(String[] args) { char code; int answer; int one; int two; String inputString; boolean quit = false; Scanner inLine = new Scanner(System.in); System.out.println("Menu: Choose the appropriate code."); System.out.println(" Q: Quit"); System.out.println(" A: Add"); System.out.println(" S: Substract"); System.out.println(" M: Multiply"); System.out.println(" D: Integer division"); System.out.println("followed by two integer operands."); do { inputString = inLine.nextLine(); code = inputString.charAt(0); if (code != 'Q' && code != 'q' ) { inputString = inputString.substring(1, inputString.length()); Scanner string = new Scanner(inputString); one = string.nextInt(); two = string.nextInt(); switch (code) { case 'a' : case 'A' : answer = (one + two); System.out.println(one + " + " + two + " is " + answer); break; case 's' : case 'S' : answer = (one - two); System.out.println(one + " - " + two + " is " + answer); break; case 'm' : case 'M' : answer = (one * two); System.out.println(one + " * " + two + " is " + answer); break; case 'd' : case 'D' : answer = (one / two); System.out.println(one + " / " + two + " is " + answer); break; default: System.out.println( "Wrong code '" + code + "'! The calculation was not performed." ); System.out.println("Please enter a valid code: " + "[A or a], [B or b], [M or m], [D or d], or [Q or q]" ); break; } } else quit = true; } while (!quit); } } The results of the test run are shown in the following table. Code First Integer Second Integer Result a a s s m d q 5 -5 7 8 8 8 -7 -8 7 -8 -8 8 5 + -7 is -2 -5 + -8 is -13 7 - 7 is 0 8 - -8 is 16 8 * -8 is -64 8 / 8 is 1 The program exits. Exercise 2: The program test run with some incorrect letters: Code First Integer Second Integer Result a a s 5 -5 7 -7 -8 7 5 + -7 is -2 -5 + -8 is -13 7 - 7 is 0 s m d 8 8 8 -8 -8 8 8 - -8 is 16 8 * -8 is -64 8 / 8 is 1 Wrong code 'x'! The calculation was not performed. x 2 6 R -9 3 w 0 7 q Please enter a valid code: [A or a], [B or b], [M or m], [D or d], or [Q or q] Wrong code 'R'! The calculation was not performed. Please enter a valid code: [A or a], [B or b], [M or m], [D or d], or [Q or q] Wrong code 'w'! The calculation was not performed. Please enter a valid code: [A or a], [B or b], [M or m], [D or d], or [Q or q] The program exits. Exercise 3: Note: Rename ‘PunctCount.java’ to ‘CountPunct.java’ The following is a sample program for Exercises 3 and 4. // Application CountPunct counts punctuation marks in a file import java.util.Scanner; import java.io.*; public class CountPunct { public static void main(String[] args) throws FileNotFoundException { FileReader file = new FileReader("Punct.dat"); Scanner inFile = new Scanner(file); String line; char symbol; int periodCt = 0; int commaCt = 0; int questionCt = 0; int colonCt = 0; int semicolonCt = 0; int blankCt = 0; int count; while (inFile.hasNextLine()) // Loop till end of data { line = inFile.nextLine(); count = 0; while (count < line.length())// Loop till end of line { symbol = line.charAt(count); // TO BE FILLED IN: count punctuation marks switch( symbol ) { case '.': periodCt++; break; case ',': commaCt++; break; case '?': questionCt++; break; case ':': colonCt++; break; case ';': semicolonCt++; break; case ' ': blankCt++; break; } count++; } } // TO BE FILLED IN: System.out.println( System.out.println( System.out.println( System.out.println( System.out.println( System.out.println( output "Number "Number "Number "Number "Number "Number of of of of of of } } The program output is Number Number Number Number Number Number of of of of of of Periods: 6 Commas: 3 Question marks: 3 Colons: 4 Semicolons: 2 Blanks: 11 Periods: " + periodCt ); Commas: " + commaCt ); Question marks: " + questionCt ); Colons: " + colonCt ); Semicolons: " + semicolonCt ); Blanks: " + blankCt ); Exercise 4: There are 11 blanks in file Punct.dat. See Exercise 3. Lesson 7-3 Exercise 1: Note 1: Rename ‘Loopng.java’ to ‘Looping.java’. Note 2: File ‘Looping.dat’ is missing. Open a new file and copy the following data to the file. Save file as ‘Looping.dat’. 1066 1492 1977 1947 1953 1066 1668 1935 1926 1492 1066 1492 1977 1947 1953 1066 1668 1935 1926 1492 -1500 Now, the program output will be The first sum is 16522 The second sum is 16522 Exercise 2: Note: The second loop only works because there is at least one positive number to read before the negative number is read. The output is the same as Exercise 1 above. The loops are now // Application Looping uses a count-controlled loop to read // and sum 10 integer values and an event-controlled loop to // read and sum values until a negative value is found. import java.io.*; import java.util.Scanner; public class Looping { public static Scanner inData; public static void main(String[] args) throws IOException { inData = new Scanner(new FileReader("Looping.dat")); int value; int counter; int sum; counter = 1; sum = 0; do {// Ten values read and summed value = inData.nextInt(); sum = sum + value; counter++; }while( counter <= 10 ); System.out.println("The first sum is " + sum); value = inData.nextInt(); sum = 0; do {// Values are read and summed until a negative is read sum = sum + value; value = inData.nextInt(); }while( value >= 0 ); System.out.println("The second sum is " + sum); } } Exercise 3: The output is the same as Exercise 1 above. The loops are now // Application Looping uses a count-controlled loop to read // and sum 10 integer values and an event-controlled loop to // read and sum values until a negative value is found. import java.io.*; import java.util.Scanner; public class Looping3 { public static Scanner inData; public static void main(String[] args) throws IOException { inData = new Scanner(new FileReader("Looping.dat")); int value; int counter; int sum; sum = 0; for (counter = 1; counter <=10; counter++) {// Ten values read and summed value = inData.nextInt(); sum = sum + value; } System.out.println("The first sum is " + sum); value = inData.nextInt(); sum = 0; for (counter = 1; value >= 0; counter++) {// Values are read and summed until a negative is read sum = sum + value; value = inData.nextInt(); } System.out.println("The second sum is " + sum); } } Exercise 4: The solutions for Exercise 1 (‘while’ loops) and Exercise 3 (‘for’ loops) will give the following results. The first sum is 16522 The second sum is 0 Exercise 2 solution (with ‘do’ loops) will crash. File Looping.d2 has eleven numbers. The first ten are positive numbers and the last number is a negative number. The Exercise 2 program fails attempting to read past the last number. The safest correction is to replace the second loop with the loop from the initial program in Exercise 1 (or the program in Exercise 3). Exercise 5: Assumption: The input file is not empty. There is at least one line to be read in. Otherwise, the solution will crash. // Application CountPunct counts punctuation marks in a file import java.util.Scanner; import java.io.*; public class CountPunct2 { public static void main(String[] args) throws FileNotFoundException { FileReader file = new FileReader("Punct.d1"); Scanner inFile = new Scanner(file); String line; char symbol; int periodCt = 0; int commaCt = 0; int questionCt = 0; int colonCt = 0; int semicolonCt = 0; int blankCt = 0; int count; do // Loop til end of data { line = inFile.nextLine(); // Loop till end of line for ( count = 0; count < line.length(); count++ ) { symbol = line.charAt(count); // TO BE FILLED IN: count punctuation marks switch( symbol ) { case '.': periodCt++; break; case ',': commaCt++; break; case '?': questionCt++; break; case ':': colonCt++; break; case ';': semicolonCt++; break; case ' ': blankCt++; break; } } }while (inFile.hasNextLine()); // TO BE FILLED IN: System.out.println( System.out.println( System.out.println( System.out.println( System.out.println( System.out.println( } } output "Number "Number "Number "Number "Number "Number of of of of of of Periods: " + periodCt ); Commas: " + commaCt ); Question marks: " + questionCt ); Colons: " + colonCt ); Semicolons: " + semicolonCt ); Blanks: " + blankCt ); Lesson 7-4 Exercise 1: The following is how a possible solution might look. // Application Switches demonstrates the use of the Switch // statement. import java.util.Scanner; public class Switches { public static void main(String[] args) { char code; int answer; int one; int two; String inputString; boolean quit = false; Scanner inLine = new Scanner(System.in); System.out.println("Menu: Choose the appropriate code."); System.out.println(" Q: Quit"); System.out.println(" A: Add"); System.out.println(" S: Substract"); System.out.println(" M: Multiply"); System.out.println(" D: Integer division"); System.out.println("followed by two integer operands."); do { inputString = inLine.nextLine(); code = inputString.charAt(0); if (code != 'Q' && code != 'q' ) { inputString = inputString.substring(1, inputString.length()); Scanner string = new Scanner(inputString); one = string.nextInt(); two = string.nextInt(); try { switch (code) { case 'a' : case 'A' : answer = (one + two); System.out.println(one + " is " + answer); break; case 's' : case 'S' : answer = (one - two); System.out.println(one + " + " + two + " - " + two + " is " + answer); break; case 'm' : case 'M' : answer = (one * two); System.out.println(one + " * " + two + " is " + answer); break; case 'd' : case 'D' : answer = (one / two); System.out.println(one + " / " + two + " is " + answer); break; default: String msg = "Wrong code '" + code + "'! The calculation was not performed.\n" + "Please enter a valid code: " + "[A or a], [B or b], [M or m], [D or d], or [Q or q]"; throw new MyException( msg ); } } catch( MyException ex ) { System.out.println( ex.getMessage() ); } } else quit = true; } while (!quit); } } The class MyException is public class MyException extends Exception { public MyException( String msg ) { super( msg ); } } A sample test run showing the error is Menu: Choose the appropriate code. Q: Quit A: Add S: Substract M: Multiply D: Integer division followed by two integer operands. a 3 4 3 + 4 is 7 s 7 4 7 - 4 is 3 m 6 6 6 * 6 is 36 M 4 5 4 * 5 is 20 f 4 5 Wrong code 'f'! The calculation was not Please enter a valid code: [A or a], [B [Q or q] W 9 5 Wrong code 'W'! The calculation was not Please enter a valid code: [A or a], [B [Q or q] Q performed. or b], [M or m], [D or d], or performed. or b], [M or m], [D or d], or The following is another solution that traps additional errors. The application was modified to handle most possible entries such as - no input (hitting the Enter button without any action entered), - incomplete inputs (e.g., S 3 – the second integer is missing), or - invalid inputs (e.g., three strings entered instead of a string and two integers). Note: this solution also uses MyException, shown above. // Application Switches demonstrates the use of the Switch // statement. import java.util.Scanner; public class Switches { static final String MSG3_PART1 = "Wrong code '"; static final String MSG3_PART2 = "'! The calculation was not performed.\n"; static final String MSG2 = "Incomplete input string: "; static final String MSG1 = "Menu: Choose the appropriate code.\n" + " Q or q: Quit\n" + " A or a: Add\n" + " S or s: Substract\n" + " M or m: Multiply\n" + " D or d: Integer division\n" + "followed by two integer operands."; public static int getNextInt( Scanner sc, String input ) throws MyException { if ( sc.hasNextInt() ) return sc.nextInt(); else throw new MyException( MSG2 + input + "\n" + MSG1 ); } public static void main(String[] args) { char code; int answer; int one; int two; String inputString; boolean quit = false; Scanner inLine = new Scanner(System.in); //display the program menu System.out.println( MSG1 ); do { inputString = inLine.nextLine(); try { if ( inputString.length() > 0 ) code = inputString.charAt(0); else { code = ' '; throw new MyException( MSG3_PART1 + code + MSG3_PART2 + MSG1 ); } if (code != 'Q' && code != 'q' ) { inputString = inputString.substring(1, inputString.length()); Scanner string = new Scanner(inputString); one = getNextInt( string, code + inputString ); two = getNextInt( string, code + inputString ); switch (code) { case 'a' : case 'A' : answer = (one + two); System.out.println(one + " is " + answer); break; case 's' : case 'S' : answer = (one - two); System.out.println(one + " is " + answer); break; case 'm' : case 'M' : answer = (one * two); System.out.println(one + " is " + answer); break; case 'd' : case 'D' : answer = (one / two); System.out.println(one + " is " + answer); + " + " + two + " - " + two + " * " + two + " / " + two break; default: throw new MyException( MSG3_PART1 + code + MSG3_PART2 + MSG1 ); } } else quit = true; } catch( MyException ex ) { System.out.println( ex.getMessage() ); } } while (!quit); } } The following is a sample test run showing the errors. Menu: Choose the appropriate code. Q or q: Quit A or a: Add S or s: Substract M or m: Multiply D or d: Integer division followed by two integer operands. a 4 5 4 + 5 is 9 S 6 9 6 - 9 is -3 m 6 2 6 * 2 is 12 D 5 -5 5 / -5 is -1 //Nothing entered. Wrong code ' '! The calculation was not performed. Menu: Choose the appropriate code. Q or q: Quit A or a: Add S or s: Substract M or m: Multiply D or d: Integer division followed by two integer operands. X 3 4 Wrong code 'X'! The calculation was not performed. Menu: Choose the appropriate code. Q or q: Quit A or a: Add S or s: Substract M or m: Multiply D or d: Integer division followed by two integer operands. R 3 Incomplete input string: R 3 Menu: Choose the appropriate code. Q or q: Quit A or a: Add S or s: Substract M or m: Multiply D or d: Integer division followed by two integer operands. RRR R R Incomplete input string: RRR R R Menu: Choose the appropriate code. Q or q: Quit A or a: Add S or s: Substract M or m: Multiply D or d: Integer division followed by two integer operands. rrrggfg Incomplete input string: rrrggfg Menu: Choose the appropriate code. Q or q: Quit A or a: Add S or s: Substract M or m: Multiply D or d: Integer division followed by two integer operands. Q Exercise 2: All classes that use File IO already use IOException; however, they could trap the errors in the programs and field them directly – see Exercise 3 for an example. Exercise 3: The following is a sample solution for Exercises 3 – 5. import java.io.*; import java.util.Scanner; public class Exceptions { static Scanner inFile; public static void main(String[] args) throws IOException { int fileTry = 1; String fileName; Scanner inName = new Scanner(System.in); System.out.println("Enter file name"); fileName = inName.nextLine(); boolean fileOk; do { fileOk = false; try { // TO BE FILLED IN: Exercise 3 inFile = new Scanner( new FileReader( fileName ) ); fileOk = true; } catch(FileNotFoundException error) { // TO BE FILLED IN: Exercise 4 System.out.println("Invalid file name. Reenter file name"); fileName = inName.nextLine(); fileTry++; } } while (!fileOk && fileTry < 4); PrintWriter outFile = new PrintWriter(new FileWriter("outData.dat")); if ( fileOk ) /* TO BE FILLED IN: Exercise 5 */ { int numDays = 0; double average; double inches = 0.0; double total = 0.0; while (inFile.hasNextFloat()) { inches = inFile.nextFloat(); total = total + inches; outFile.println(inches); numDays++; } if (numDays == 0) System.out.println("Average cannot be computed " + " for 0 days."); else { average = total / numDays; outFile.println("The average rainfall over " + numDays + " days is " + average); } inFile.close(); } else outFile.println( "File not found!" ); // TO BE FILLED IN: Exercise 5 outFile.close(); } } Exercise 4: See Exercise 3. Exercise 5: See Exercise 3. Exercise 6: The following is printed to outData.dat. 2.299999952316284 3.0999999046325684 0.30000001192092896 1.100000023841858 2.200000047683716 2.0999999046325684 0.0 0.4000000059604645 0.7599999904632568 0.5 1.0 0.5 The average rainfall over 12 days is 1.1883333201209705 Exercise 7: The following is the output. Enter file name NoFile.txt Invalid file name. Reenter file name MyFile.dat Invalid file name. Reenter file name AnyFile.d1 Invalid file name. Reenter file name xyz.try Lesson 7-5 Exercise 1: ‘break;’ should be added in each ‘case’ of the ‘switch’ statement. Exercise 2: Set file name to “Bug.dat” Exercise 3: Add ‘counter++;’ to the bottom of the ‘do’ loop. Exercise 4: Remove ‘counter++;’ from the ‘for’ loop. The following is a sample solution for Exercises 1 – 4. // Application Bugs demonstrates various looping structures. import java.io.*; import java.util.Scanner; public class Bugs { public static Scanner inData; public static void main(String[] args) throws IOException { int fileFound; try { inData = new Scanner(new FileReader("Bug.dat")); fileFound = 1; } catch (IOException exception) { fileFound = 2; } int value; switch (fileFound) { case 2 : System.out.println("Bugs.dat not found"); break; // added to correct error in Exercise 1 case 1 : // do loop int counter = 1; int sum = 0; do { value = inData.nextInt(); sum = sum + value; counter++; // added to correct bug in Exercise 3 } while (counter <= 10); System.out.println(sum); // for loop sum = 0; for (counter = 1; counter <= 10; counter++) { value = inData.nextInt(); sum = sum + value; //counter++; // removed to correct bug in Exercise 4 } System.out.println(sum); break; // added to correct error in Exercise 1 } } } Now, the application output is 55 55