1. Trang chủ
  2. » Khoa Học Tự Nhiên

deitel instructors manual for simply c (2004)

668 7 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

www.elsolucionario.net www.elsolucionario.net C O N T E N Drawing Application T S Introducing Computers, the Internet and C# Welcome Application Introducing the Visual Studio NET IDE Welcome Application Introduction to Visual Programming Designing the Inventory Application 25 Introducing TextBoxes and Buttons Completing the Inventory Application 32 Introducing Programming Enhancing the Inventory Application 51 Introducing Variables, Memory Concepts and Arithmetic Wage Calculator Application 71 Introducing Algorithms, Pseudocode and Program Control Dental Payment Application 94 Introducing CheckBoxes and Message Dialogs Car Payment Calculator Application 131 Introducing the while Repetition Statement 10 Class Average Application 153 Introducing the do…while Repetition Statement 11 Interest Calculator Application 175 Introducing the for Repetition Statement 12 Security Panel Application 197 Introducing the switch Multiple-Selection Statement 13 Enhancing the Wage Calculator Application 226 Introducing Methods 14 Shipping Time Application Using DateTimes and Timers i www.elsolucionario.net 248 ii 15 Brief Table of Contents Fund Raiser Application 267 Introducing Scope and Pass-by-Reference 16 Craps Game Application 285 Introducing Random-Number Generation 17 Flag Quiz Application 306 Introducing One-Dimensional Arrays and ComboBoxes 18 Student Grades Application 330 Introducing Two-Dimensional Arrays and RadioButtons 19 Microwave Oven Application 355 Building Your Own Classes and Objects 20 Shipping Hub Application 395 Introducing Collections, the foreach Statement and Access Keys 21 “Cat and Mouse” Painter Application 427 Introducing the Graphics Object and Mouse Events 22 Typing Application 447 Introducing Keyboard Events, Menus and Dialogs 23 Screen Scraping Application 475 Introducing string Processing 24 Ticket Information Application 497 Introducing Sequential-Access Files 25 ATM Application 521 Introducing Database Programming 26 Check Writer Application 555 Introducing Graphics and Printing 27 Phone Book Application 584 Introducing Multimedia Using Microsoft Agent 28 Bookstore Application: Web Applications 611 Introducing Internet Information Services 29 Bookstore Application: Client Tier 614 Introducing Web Controls 30 Bookstore Application: Information Tier 621 Examining the Database and Creating Database Components 31 Bookstore Application: Middle Tier 625 Introducing Code-Behind Files 32 Enhanced Car Payment Calculator Application Introducing Exception Handling www.elsolucionario.net 642 T U T O R I A L Drawing Application Introducing Computers, the Internet and C# Solutions www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial Drawing Application Instructor’s Manual Exercise Solutions Tutorial MULTIPLE-CHOICE QUESTIONS 1.1 The HyperText Markup Language was developed a) by ARPA c) before the Internet 1.2 Microsoft’s development b) at CERN by Tim Berners-Lee d) as a replacement for the Internet initiative integrates the Internet and the Web into software a) NET c) Windows b) BASIC d) W3C 1.3 TextBoxes, Buttons and RadioButtons are examples of a) platforms c) IDEs b) high-level languages d) controls is an example of primary memory 1.4 a) TCP c) ALU 1.5 C# is an example of a(n) accomplish more substantial tasks a) machine c) high-level b) RAM d) CD-ROM language, in which single program statements b) intermediate-level d) assembly 1.6 Which protocol is primarily intended to create a “network of networks?” a) TCP c) OOP b) IP d) FCL 1.7 A major benefit of programming is that it produces software that is more understandable and better organized than software produced with previously used techniques a) object-oriented c) procedural b) centralized d) HTML 1.8 NET’s collection of prepackaged classes and methods is called the a) NCL c) FCL b) WCL d) PPCM 1.9 The information-carrying capacity of communications lines is called a) networking c) traffic b) secondary storage d) bandwidth 1.10 Which of these programming languages was specifically created for NET? a) C# c) BASIC b) C++ d) Visual Basic Answers: 1.1) b 1.2) a 1.3) d 1.4) b 1.5) c 1.6) b 1.7) a 1.8) c 1.9) d 1.10) a EXERCISES 1.11 Categorize each of the following items as either hardware or software: a) CPU c) Input unit e) A C# program b) Compiler d) A word-processor program www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Introducing Computers, the Internet and C# Solutions Tutorial Answers: a) hardware b) software c) hardware d) software e) software 1.12 Translator programs, such as assemblers and compilers, convert programs from one language (referred to as the source language) to another language (referred to as the target language) Determine which of the following statements are true and which are false: a) A compiler translates high-level-language programs into target-language programs b) An assembler translates source-language programs into machine-language programs c) A compiler translates source-language programs into target-language programs d) Machine languages are generally machine independent e) A machine-language program requires translation before it can be run on a computer Answers: a) True b) True c) True d) False Machine languages are generally machine dependent e) False A machine language program is native to that specific machine and can be run without translation 1.13 Computers can be thought of as being divided into six units a) Which unit can be thought of as “the boss” of the other units? b) Which unit is the high-capacity “warehouse” that retains information even when the computer is powered off? c) Which unit might determine whether two items stored in memory are identical? d) Which unit obtains information from devices like the keyboard and mouse? Answers: a) CPU b) Secondary storage unit c) ALU d) Input unit 1.14 Expand each of the following acronyms: a) W3C c) OOP e) HTML b) TCP/IP d) FCL Answers: a) World Wide Web Consortium b) Transmission Control Protocol/Internet Pro- tocol c) Object-oriented programming d) Framework Class Library e) HyperText Markup Language 1.15 What are the advantages to using object-oriented programming techniques? Answer: Programs that use object-oriented programming techniques are easier to understand, correct and modify The key advantage with using object-oriented programming is that it tends to produce software that is more understandable because it is better organized and has fewer maintenance requirements than software produced with earlier methodologies OOP helps the programmer build applications faster by reusing existing software components OOP also helps programmers create new software components that can be reused on future software-development projects www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved T U T O R I A L Welcome Application Introducing the Visual Studio® NET IDE Solutions www.elsolucionario.net © Copyright 1992-2004by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial Welcome Application Instructor’s Manual Exercise Solutions Tutorial MULTIPLE-CHOICE QUESTIONS 2.1 The integrated development environment (IDE) is used for creating applications written in NET programming languages such as C# a) Solution Explorer c) Visual Studio NET b) Gates d) Microsoft 2.2 The.cs filename extension indicates a a) C# file c) help file b) dynamic help file d) cool solution file 2.3 The pictures on toolbar Buttons are called a) prototypes c) tool tips 2.4 The b) icons d) tabs allows programmers to modify controls visually, without writing code a) Properties window c) menu bar 2.5 The Box’s area b) Solution Explorer d) Toolbox hides the Toolbox when the mouse pointer is moved outside the Tool- a) component-selection feature c) pinned command b) Auto Hide feature d) minimize command 2.6 A appears when the mouse pointer is positioned over an IDE toolbar icon for a few seconds a) drop-down list c) tool tip b) menu d) down arrow 2.7 The Visual Studio NET IDE provides a) help documentation c) windows for accessing project files 2.8 The nity b) a toolbar d) All of the above contains a list of helpful links, such as Get Started and Online Commu- a) Solution Explorer window c) Start Page 2.9 The Properties window contains a) the component object box c) menus b) Properties window d) Toolbox link b) a Solution Explorer d) a menu bar can be enhanced by adding reusable controls such as Buttons 2.10 A a) component c) icon b) Form d) property 2.11 For Web browsing, Visual Studio NET includes a) Web View c) a Web tab 2.12 An application’s GUI can include a) toolbars c) menus b) Excel d) Internet Explorer b) icons d) All of the above www.elsolucionario.net © Copyright 1992-2004by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Introducing the Visual Studio® NET IDE Solutions 2.13 The Tutorial does not contain a pin icon a) Dynamic Help window c) Toolbox window b) Solution Explorer window d) active tab 2.14 When clicked, in the Solution Explorer window will expand nodes and will collapse nodes a) minus boxes; plus boxes c) up arrows; down arrows 2.15 Form b) plus boxes; minus boxes d) left arrows; right arrows specify attributes such as size and position a) nodes c) properties b) inputs d) title bars Answers: 2.1) c 2.2) a 2.3) b 2.4) a 2.5) b 2.6) c 2.7) d 2.8) c 2.9) a 2.10) b 2.11) d 2.12) d 2.13) d 2.14) b 2.15) c EXERCISES 2.16 (Closing and Opening the Start Page) In this exercise, you will learn how to close and reopen the Start Page (Fig 2.30) To accomplish this task, perform the following steps: Close box Figure 2.30 Showing the Start Page a) Close Visual Studio NET if it is open by clicking its close box b) Start Visual Studio NET c) Close the Start Page by clicking its close box (Fig 2.30) d) Select Help > Show Start Page to display the Start Page 2.17 (Enabling Auto Hide for the Solution Explorer Window) In this exercise, you will learn how to use the Solution Explorer window’s Auto Hide feature (Fig 2.31) by performing the following steps: Vertical pin icon Figure 2.31 Enabling Auto Hide a) Open the Start Page b) In the Projects tab (displayed by default), click the Open Project Button to display the Open Project dialog You can skip to Step e if the Welcome application is already open c) In the Open Project dialog, navigate to C:\SimplyCSP\Welcome, and click Open d) In the Open Project dialog, select Welcome.sln, and click Open e) Position the mouse pointer on the vertical pin icon in the Solution Explorer window’s title bar After a few seconds, a tool tip appears displaying the words Auto Hide www.elsolucionario.net © Copyright 1992-2004by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial 32 Enhanced Car Payment Calculator Application 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 } 650 // display a message if the user did not // input integer values catch ( FormatException formatExceptionParameter ) { MessageBox.Show( "Please enter integers for the lower and upper " + "bounds.", "Invalid Number Format", MessageBoxButtons.OK, MessageBoxIcon.Error ) } // end catch block txtPrimeNumbers.Text = strOutput; } // end method btnCalculatePrimes_Click } // end class FrmPrimeNumbers 32.13 (Enhanced Letterhead Designer Application) Modify the Letterhead application (Exercise 26.13) to use exception handling to process the FileNotFoundException that may occur when the user specifies the image that will serve as the letterhead (Fig 32.17) We will define what a FileNotFoundException is shortly The application should still allow users to design stationery for company documents Figure 32.17 Enhanced Letterhead application a) Copying the template to your working directory Copy the directory C:\Examples\ Tutorial32\Exercises\EnhancedLetterhead to your C:\SimplyCSP directory b) Opening the application’s template file Double click Letterhead.sln in the EnhancedLetterhead directory to open the application c) Adding a try block to the btnAdd_Click event handler Find the btnAdd_Click event handler Enclose the body of btnAdd_Click in a try block d) Adding a catch block to the btnAdd_Click event handler Add a catch block that catches any FileNotFoundExceptions that may occur in the try block that you added in Step c A FileNotFoundException is thrown when you attempt to access a file that does not exist Inside the catch block, add code to display an error message dialog www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved 651 Introducing Exception Handling Solutions Tutorial 32 e) Running the application Select Debug > Start to run your application Enter an incorrect path for your image, and ensure that a MessageBox appears indicating the invalid input f) Closing the application Close your running application by clicking its close box g) Closing the IDE Close Visual Studio NET by clicking its close box Answer: 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // Exercise 32.13 Solution // Letterhead.cs (Enhanced) using using using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; System.Drawing.Printing; System.IO; namespace Letterhead { /// /// Summary description for FrmLetterHead /// public class FrmLetterHead : System.Windows.Forms.Form { // PictureBox to display the letterhead private System.Windows.Forms.PictureBox picImage; // TextBox to input letterhead text private System.Windows.Forms.TextBox txtInformation; // Label and TextBox to input image location private System.Windows.Forms.Label lblImage; private System.Windows.Forms.TextBox txtImage; // Button to add the image private System.Windows.Forms.Button btnAdd; // Button to preview the letterhead private System.Windows.Forms.Button btnPreview; // Button to print the letterhead private System.Windows.Forms.Button btnPrint; // PrintPreviewDialog to preview and print the letterhead private System.Windows.Forms.PrintPreviewDialog objPreview; /// /// Required designer variable /// private System.ComponentModel.Container components = null; // create font object Font m_objFont; public FrmLetterHead() { // www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial 32 Enhanced Car Payment Calculator Application 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 652 // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent // call // } /// /// Clean up any resources being used /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } // Windows Form Designer generated code /// /// The main entry point for the application /// [STAThread] static void Main() { Application.Run( new FrmLetterHead() ); } // PrintPage event raised for each page to be printed private void objPrintDocument_PrintPage( object sender, PrintPageEventArgs e ) { float fltYPosition; float fltXPosition; float fltLeftMargin = e.MarginBounds.Left; float fltTopMargin = e.MarginBounds.Top; string strPath; // get location of image strPath = txtImage.Text; // make sure image location was provided if ( strPath != "" ) { Image objImage; objImage = Image.FromFile( strPath ); // print image so it is on top of page e.Graphics.DrawImage( Image.FromFile( strPath ), fltLeftMargin + picImage.Location.X, fltTopMargin + picImage.Location.Y, www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved 653 Introducing Exception Handling Solutions 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 Tutorial 32 picImage.Size.Width, picImage.Size.Height ); } // if contact information is provided, print data if ( txtInformation.Text != "" ) { // specifies font of text m_objFont = new Font( "Tahoma", 12, FontStyle.Bold ); fltXPosition = fltLeftMargin + txtInformation.Location.X; fltYPosition = fltTopMargin + txtInformation.Location.Y; // print information e.Graphics.DrawString( txtInformation.Text, m_objFont, Brushes.Black, fltXPosition, fltYPosition ); } // indicate there are no more pages to print e.HasMorePages = false; } // end method objPrintDocument_PrintPage // print the document private void btnPrint_Click( object sender, System.EventArgs e ) { // create new object to assist in printing PrintDocument objPrintDocument = new PrintDocument(); // add PrintPage event handler objPrintDocument.PrintPage += new PrintPageEventHandler( objPrintDocument_PrintPage ); // print the document objPrintDocument.Print(); } // end method btnPrint_Click // display document in print preview dialog private void btnPreview_Click( object sender, System.EventArgs e ) { // create new object to assist in previewing PrintDocument objPrintDocument = new PrintDocument(); // add PrintPage event handler objPrintDocument.PrintPage += new PrintPageEventHandler( objPrintDocument_PrintPage ); objPreview.Document = objPrintDocument; // specify document objPreview.ShowDialog(); // show print preview } // end method btnPreview_Click // add the specified image to the Image control private void btnAdd_Click( object sender, System.EventArgs e ) { // try to import the image specified try www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial 32 Enhanced Car Payment Calculator Application { 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 } ▲ What does this code do? 654 if ( txtImage.Text != "" ) { picImage.Image = Image.FromFile( txtImage.Text ); } else { // display an error if the user did not enter anything MessageBox.Show( "You must enter a path for your image.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Information ); } } // handle case where the image could not be found catch ( FileNotFoundException fileNotFoundExceptionParameter ) { MessageBox.Show( "Please enter a valid file name.", "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } // end method btnAdd_Click } // end class FrmLetterHead 32.14 What does the following code do, assuming that dblValue1 and dblValue2 are both declared as doubles? 10 11 12 13 14 15 try { dblValue1 = Double.Parse( txtInput1.Text ); dblValue2 = Double.Parse( txtInput2.Text ); txtOutput.Text = Convert.ToString( dblValue1 * dblValue2 ); } catch ( FormatException formatExceptionParameter ) { MessageBox.Show( "Please enter decimal values.", "Invalid Number Format", MessageBoxButtons.OK, MessageBoxIcon.Error ); } Answer: This code multiplies two doubles if both inputs in txtInput1 and txtInput2 can be converted to type double (that is, they are decimal or integer values) Otherwise it displays an error message dialog that informs the user to enter decimal values in the TextBoxes The complete code reads: // Exercise 32.14 Solution // Multiplier.cs using System; www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved 655 Introducing Exception Handling Solutions 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 using using using using using Tutorial 32 System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; namespace Multiplier { /// /// Summary description for FrmMultiplier /// public class FrmMultiplier : System.Windows.Forms.Form { // Label and TextBox for first value private System.Windows.Forms.Label lblValue1; private System.Windows.Forms.TextBox txtInput1; // Label and TextBox for second value private System.Windows.Forms.Label lblValue2; private System.Windows.Forms.TextBox txtInput2; // Label and TextBox for output private System.Windows.Forms.Label lblProduct; private System.Windows.Forms.TextBox txtOutput; // Button to perform multiplication private System.Windows.Forms.Button btnMultiply; /// /// Required designer variable /// private System.ComponentModel.Container components = null; public FrmMultiplier() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent // call // } /// /// Clean up any resources being used /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial 32 Enhanced Car Payment Calculator Application 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 } ▲ What’s wrong with this code? 656 // Windows Form Designer generated code /// /// The main entry point for the application /// [STAThread] static void Main() { Application.Run( new FrmMultiplier() ); } // handles btnMultiply's Click event private void btnMultiply_Click( object sender, System.EventArgs e ) { double dblValue1; double dblValue2; try { dblValue1 = Double.Parse( txtInput1.Text ); dblValue2 = Double.Parse( txtInput2.Text ); txtOutput.Text = Convert.ToString( dblValue1 * dblValue2 ); } catch ( FormatException formatExceptionParameter ) { MessageBox.Show( "Please enter decimal values.", "Invalid Number Format", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } // end method btnMultiply_Click } // end class FrmMultiply 32.15 The following code should add integers from two TextBoxes and display the result in txtResult Assume that intValue1 and intValue2 are declared as ints Find the error(s) in the following code: try { intValue1 = Int32.Parse( txtInput1.Text ); www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved 657 Introducing Exception Handling Solutions 10 11 12 13 14 15 Tutorial 32 intValue2 = Int32.Parse( txtInput2.Text ); txtOutput.Text = Convert.ToString( intValue1 + intValue2 ); catch ( ) { MessageBox.Show( "Please enter valid ints.", "Invalid Number Format", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } Answer: There are two errors in this code First, the catch block appears inside the try block All catch blocks must follow immediately after the try block Second, you will need to specify which type of exception is being caught between the parentheses after the catch statement (in this case, a FormatException) The complete incorrect code reads: 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 // Exercise 32.15 Solution // Addition.cs (Incorrect) using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; namespace Addition { /// /// Summary description for FrmAddition /// public class FrmAddition : System.Windows.Forms.Form { // Label and TextBox for first value private System.Windows.Forms.Label lblValue1; private System.Windows.Forms.TextBox txtInput1; // Label and TextBox for second value private System.Windows.Forms.Label lblValue2; private System.Windows.Forms.TextBox txtInput2; // Label and TextBox for output private System.Windows.Forms.Label lblProduct; private System.Windows.Forms.TextBox txtOutput; // Button to perform addition private System.Windows.Forms.Button btnAdd; /// /// Required designer variable /// private System.ComponentModel.Container components = null; public FrmAddition() { // // Required for Windows Form Designer support // www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial 32 Enhanced Car Payment Calculator Application catch block should not be inside try block, specify exception type in catch statement 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 658 InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent // call // } /// /// Clean up any resources being used /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } // Windows Form Designer generated code /// /// The main entry point for the application /// [STAThread] static void Main() { Application.Run( new FrmAddition() ); } // handles btnAdd's Click event private void btnAdd_Click( object sender, System.EventArgs e ) { int intValue1; int intValue2; try { intValue1 = Convert.ToInt32( txtInput1.Text ); intValue2 = Convert.ToInt32( txtInput2.Text ); txtOutput.Text = Convert.ToString( intValue1 + intValue2 ); catch ( ) { MessageBox.Show( "Please enter valid integers.", "Invalid Number Format", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } } // end method btnAdd_Click www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved 659 Introducing Exception Handling Solutions 103 104 105 } Tutorial 32 } // end class FrmAddition Answer: The complete corrected code should read: 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 // Exercise 32.15 Solution // Addition.cs (Correct) using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; namespace Addition { /// /// Summary description for FrmAddition /// public class FrmAddition : System.Windows.Forms.Form { // Label and TextBox for first value private System.Windows.Forms.Label lblValue1; private System.Windows.Forms.TextBox txtInput1; // Label and TextBox for second value private System.Windows.Forms.Label lblValue2; private System.Windows.Forms.TextBox txtInput2; // Label and TextBox for output private System.Windows.Forms.Label lblProduct; private System.Windows.Forms.TextBox txtOutput; // Button to perform addition private System.Windows.Forms.Button btnAdd; /// /// Required designer variable /// private System.ComponentModel.Container components = null; public FrmAddition() { // // Required for Windows Form Designer support // InitializeComponent(); www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial 32 Enhanced Car Payment Calculator Application 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 660 // // TODO: Add any constructor code after InitializeComponent // call // } /// /// Clean up any resources being used /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } // Windows Form Designer generated code /// /// The main entry point for the application /// [STAThread] static void Main() { Application.Run( new FrmAddition() ); } // handles btnAdd's Click event private void btnAdd_Click( object sender, System.EventArgs e ) { int intValue1; int intValue2; try { intValue1 = Int32.Parse( txtInput1.Text ); intValue2 = Int32.Parse( txtInput2.Text ); txtOutput.Text = Convert.ToString( intValue1 + intValue2 ); } catch ( FormatException formatExceptionParameter ) { MessageBox.Show( "Please enter valid integers.", "Invalid Number Format", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } // end method btnAdd_Click } // end class FrmAddition www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved 661 Introducing Exception Handling Solutions Tutorial 32 105 } ▲ Programming Challenge 32.16 (Enhanced Vending Machine Application) The Vending Machine application from Tutorial has been modified to use exception handling to process the IndexOutOfRangeExceptions that occur when selecting items out of the range through (Fig 32.18) This type of exception will be defined shortly To get a snack, the user must type the number of the desired snack in the TextBox, then press the Dispense Snack: Button The name of the snack is displayed in the output Label Figure 32.18 Vending Machine application a) Copying the template to your working directory Copy the directory C:\Examples\ Tutorial32\Exercises\EnhancedVendingMachine to your C:\SimplyCSP directory b) Opening the application’s template file Double click VendingMachine.sln in the EnhancedVendingMachine directory to open the application c) Adding a try block Find the btnDispense_Click event handler Enclose all of the code in the event handler in a try block www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial 32 Enhanced Car Payment Calculator Application 662 d) Adding a catch block Add a catch block that catches any FormatExceptions that may occur in the try block that you added to btnDispense_Click in Step c Inside the catch block, add code to display an error message dialog e) Adding a second catch block Immediately following the catch block you added in Step c, add a second catch block to catch any IndexOutOfRangeExceptions that may occur An IndexOutOfRangeException occurs when the application attempts to access an array with an invalid index Inside the catch block, add code to display an error message dialog f) Running the application Select Debug > Start to run your application Make an out of range selection (for instance, 32) and click the Dispense Snack Button Verify that the proper MessageBox is displayed for the invalid input Enter letters for a selection and click the Dispense Snack Button Verify that the proper MessageBox is displayed for the invalid input g) Closing the application Close your running application by clicking its close box h) Closing the IDE Close Visual Studio NET by clicking its close box Answers: 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 // Exercise 32.16 Solution // VendingMachine.cs (Enhanced) using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; namespace VendingMachine { /// /// Summary description for FrmVendingMachine /// public class FrmVendingMachine : System.Windows.Forms.Form { // Panel enclosing snack choices private System.Windows.Forms.Panel windowPanel; // Labels and PictureBoxes for each snack private System.Windows.Forms.Label lbl0; private System.Windows.Forms.Label lbl1; private System.Windows.Forms.Label lbl2; private System.Windows.Forms.Label lbl3; private System.Windows.Forms.Label lbl4; private System.Windows.Forms.Label lbl5; private System.Windows.Forms.Label lbl6; private System.Windows.Forms.Label lbl7; private System.Windows.Forms.PictureBox picItem0; private System.Windows.Forms.PictureBox picItem1; private System.Windows.Forms.PictureBox picItem2; private System.Windows.Forms.PictureBox picItem3; private System.Windows.Forms.PictureBox picItem4; private System.Windows.Forms.PictureBox picItem5; private System.Windows.Forms.PictureBox picItem6; private System.Windows.Forms.PictureBox picItem7; // Label for the output private System.Windows.Forms.Label lblOutput; // Label and TextBox for the user's selection www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved 663 Introducing Exception Handling Solutions 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 Tutorial 32 private System.Windows.Forms.Label lblSelection; private System.Windows.Forms.TextBox txtSelection; // Button to dispense the snack private System.Windows.Forms.Button btnDispense; /// /// Required designer variable /// private System.ComponentModel.Container components = null; // declare an array of snack names string[] strSnacks = { "Chocolate Chip Cookie", "Bubble Gum", "Plain Pretzel", "Soda", "Salted Pretzel", "Oatmeal Cookie", "Diet Soda", "Sugar-free Gum" }; public FrmVendingMachine() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent // call // } /// /// Clean up any resources being used /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } // Windows Form Designer generated code /// /// The main entry point for the application /// [STAThread] static void Main() { Application.Run( new FrmVendingMachine() ); } // method to dispense snack private void btnDispense_Click( object sender, System.EventArgs e ) www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved Tutorial 32 Enhanced Car Payment Calculator Application 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 } 664 { // try to get user input try { // get user input int intSelection = Int32.Parse( txtSelection.Text ); lblOutput.Text = Convert.ToString( strSnacks[ intSelection ] ) + " has been dispensed"; } // handle case when user enters invalid input catch ( FormatException formatExceptionParameter ) { MessageBox.Show( "Please enter an integer value.", "Number Format Exception", MessageBoxButtons.OK, MessageBoxIcon.Error ); } // handle case when user inputs number not in array bounds catch ( IndexOutOfRangeException indexExceptionParameter ) { MessageBox.Show( "Please enter a value between 0-7.", "Array Index Out of Bounds Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } // end method btnDispense_Click } // end class FrmVendingMachine www.elsolucionario.net © Copyright 1992-2004 by Deitel & Associates, Inc and Pearson Education Inc All Rights Reserved ... directory C: Examples Tutorial05ExercisesAccountInformation to your C: SimplyCSP directory b) Opening the application’s template file Double click AccountInformation.sln in the AccountInformation... collection of prepackaged classes and methods is called the a) NCL c) FCL b) WCL d) PPCM 1.9 The information-carrying capacity of communications lines is called a) networking c) traffic b) secondary storage... 3.33 Calculator GUI a) Creating a new project Open Visual Studio NET Create a new project in your C: SimplyCSP directory named Calculator b) Renaming the Form file Name the Form file Calculator.cs

Ngày đăng: 16/10/2021, 15:36

Xem thêm: