Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 13 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
13
Dung lượng
0,93 MB
Nội dung
Lab Guide Lab version:1.0.0 Last updated:7/19/2015 Page Overview An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program In this lab, you will write simple applications to practice handling exception and using assert statement in Java Objectives Once you have completed this lab, you will understand: How to handling exception in java Benefit of using asert statement Exercises This Hands-On Lab is comprised by the following exercises: Exception Try-catch-Finally Create your own exception classes Using Assert Estimated time to complete this lab: hours Page Index EXERCISE 1: EXCEPTION Task - Create SendSMS Project Task - Create MobilePhone Class Task - Write code in MobilePhone.java Task - Write a PhoneTest class to demonstrate exception handling Task - Execute your program EXERCISE 2: TRY-CATH-FINALLY Task - Create TryCatchFinally Class Task - Enter following code in TryCatchFinally.java Task - Execute your program EXERCISE 3: 10 ACCOUNT IN A BANK 11 11 Task - Create Account class 12 Task - Create AccountTest class 12 Task - Create InsufficientFundException class 13 Task - Create NegativeAmountException class 13 Page Next Step Exercise 1: Exception In this exercise, you will write a program to demonstrate exception handling You have to create: MobilePhone class to store mobile phone numbers and send a messages to one of of numbers store in the array PhoneTest class to demonstrate exception handling Class diagram of the program: Task - Create SendSMS Project Choose "File" menu ⇒ "New" ⇒ "Java project" The "New Java Project" dialog pops up In the "Project name" field, enter " SendSMS" Check "Use default location" In the "JRE" box, select your JDK version installed on your system Click "Finish" Task - Create MobilePhone Class In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up In "Name" field, enter "MobilePhone" Click "Finish" Page Task - Write code in MobilePhone.java Import libraries import java.util.InputMismatchException; import java.util.Scanner; Variable to store the mobile numbers int phoneNumbers[]; Variable to store the message text String message; Constructor public MobilePhone() { message = ""; } Method to construct an array and add numbers to it public void setPhoneNumbers() { Scanner input = new Scanner(System.in); try { System.out.println("Enter the number of mobile numbers to store:"); int size = input.nextInt(); phoneNumbers = new int[size]; for(int index = 0;index < phoneNumbers.length;index++) { System.out.println("Enter a phone number:"); phoneNumbers[index] = input.nextInt(); } } catch(NegativeArraySizeException e) { System.out.println("Exception occurred - " + "Array size should be a positive value."); } catch(InputMismatchException e) { System.out.println("Exception occurred - Data type mismatch." + " Enter non-zero numeric value and try again."); } catch(Exception e) { System.out.println("Exception occurred - " + e.getMessage()); } } Page Method to display the mobile numbers stored in the database(array) public void getPhoneNumbers() { System.out.println("The mobile phone database consists of following " + "phone numbers:"); for(int index = 0;index < phoneNumbers.length;index++) { System.out.println(index + " " + phoneNumbers[index]); } } Method to send a message to a mobile number based on the user input public void sendMessage() { Scanner input = new Scanner(System.in); try { getPhoneNumbers(); System.out.println("Enter the index of phone number to which you" + " want to send the message:"); int index = input.nextInt(); System.out.println("Enter the message text: "); // Accept message text until the use press the Enter key input.useDelimiter("\n");//hoac dung input.nextLine() this.message = input.next(); System.out.printf("\nSending message [%s] to [%d] please " + "wait\n", this.message, this.phoneNumbers[index]); System.out.printf("\nMessage successfully sent."); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception occurred - Invalid index."); } catch(InputMismatchException e) { System.out.println("Exception occurred - Data type mismatch " + "Check the data type and try again"); } catch(NullPointerException e) { System.out.println("Exception occurred - The database of mobile " + "numbers is empty."); } catch(Exception e) { System.out.println("Exception occurred - " + e.getMessage()); } } } Page Task - Write a PhoneTest class to demonstrate exception handling In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up In "Name" field, enter "PhoneTest " Check "public static void main(String[] args)" box Click "Finish" Write code for main() method: public static void main(String[] args) { // Create an instance of MobilePhone class MobilePhone objNokia = new MobilePhone(); Scanner input = new Scanner(System.in); // Variable to store user's choice byte choice ; // Iterate until the chooses to exit the application { System.out.printf("\nSelect an operation from the following:"); System.out.println("\n1 Add phone numbers \n2 Send Message\n3 Exit"); // Accept the choice from the user System.out.println("Enter the choice: "); choice = input.nextByte(); // Invoke the methods of MobilePhone class depending on the // operation selected by the user if(choice == 1) { objNokia.setPhoneNumbers(); } else if (choice == 2) { objNokia.sendMessage(); } } while(choice != 3); } Page Task - Execute your program To run the program, right-click anywhere on the source file " PhoneTest.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel See some exceptions what shall appear: Exercise 2: Try-cath-finally In this exercise you will practice the structure try – catch-finally Remember: If a catch-block catches that exception class or catches a superclass of that exception, the statement in that catch-block will be executed The statements in the finally-block are then executed after that catch-block The program Page continues into the next statement after the try-catch-finally, unless it is pre-maturely terminated or branch-out Task - Create TryCatchFinally Class In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up In "Name" field, enter " TryCatchFinally " Check "public static void main(String[] args)" box Click "Finish" Task - Enter following code in TryCatchFinally.java import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class TryCatchFinally { public static void main(String[] args) { try { // main logic System.out.println("Start of the main logic"); System.out.println("Try opening a file "); Scanner in = new Scanner(new File("test.in")); System.out.println("File Found, processing the file "); System.out.println("End of the main logic"); } catch (FileNotFoundException e) { // error handling separated from the main logic System.out.println("File Not Found caught "); } finally { // always run regardless of exception status System.out.println("finally-block runs regardless of the state of exception"); } // after the try-catch-finally System.out.println("After try-catch-finally"); } } Page Task - Execute your program To run the program, right-click anywhere on the source file "TryCatchFinally.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel Edit above code to understand how to try-catch-finally work (for example: add more type of exceptions or add a goto statement) Page 10 Exercise 3: Account in a Bank The management of the A Bank is looking at automation as a means to save time and effort required in their work In order to achieve this, the management has planned to computerize the following transactions: Creating a new account Withdrawing money from an account Depositing money in an account The CEO of the company and a team of experts have chosen your company to provide a solution for the same Consider yourself to be a part of the team that implements the solution for designing the application Create an application using exceptions and assertions to implement the transactions The application should consist of the following classes Page 11 Account.java Account Test.java InsufficientFundException.java NegativeAmountException.java Each class has a specific purpose and functionality The descriptions of each class are as follows Task - Create Account class (The Account class represents an actual bank account It stores the following details of a bank account) customerName accountNumber accountbalance void displayAccountDetails() : This method displays the details of the account void withdraw() : This method is used to withdraw money from an account This method accepts the account number and the amount to be withdrawn from the account The method then searches in the array of accounts for the account number Use assertions for checking whether the account number and the amount to be withdrawn are positive Also use an assertion to check if the array of accounts contains a minimum of one account record The method also throws the user-defined exception InsufficientFund***ception in case the amount to be withdrawn exceeds void deposit() :This method is used to deposit money in an account The account number and the amount to be deposited in the account is accepted from the user Use an assertion to check whether the account number is positive The method searches for the account number and deposits the amount in the account if it exists The displayAccountDetails() method is called if the operation succeeds Use appropriate try catch blocks to handle all the possible exceptions that can be thrown due to the user inputs A user-defined exception is thrown if the account number does not exist Task - Create AccountTest class (The AccountTest class is a java main class used to test the Account class It creates an instance of the Account class and displays the following menu of options to the user) Create a new account Withdraw Cash Page 12 Deposit cash Exit The user can select any of the options and a corresponding method is invoked on the instance of the Bank class Use an assertion to check for the control-flow invariant in case the user types an invalid option The application exits when the Exit option is selected Task - Create InsufficientFundException class This is a user-defined exception class derived from the base class Exception This exception is thrown when the user tries to withdraw more money than the current account balance Task - Create NegativeAmountException class This is a user-defined exception class derived from the base class Exception This exception is thrown when the user tries to withdraw or deposit a negative amount Next Step Summary In this lab, you have learned how to handle exception and created your own Exception classes in Java, In addition, you have known the benefit of using assert statement, and how to using it in your code Page 13 ... about your program In this lab, you will write simple applications to practice handling exception and using assert statement in Java Objectives Once you have completed this lab, you will understand:... Exercises This Hands-On Lab is comprised by the following exercises: Exception Try-catch-Finally Create your own exception classes Using Assert Estimated time to complete this lab: hours Page... is thrown when the user tries to withdraw or deposit a negative amount Next Step Summary In this lab, you have learned how to handle exception and created your own Exception classes in Java, In