Question

In: Computer Science

*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define...

*IN JAVA*

EXCEPTION HANDLING

Concept Summary:

1. Use of try… catch in a program

2. Define an exception class and call it from the driver program.

For this lab you will complete two parts.

Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error.

Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will enter the time as a 4-digit number with no colon.

Submission Guidelines: You will turn in 3 program files.

Part (a) has one program file

Part (b) requires two program files. (Note: C# Students can turn in one program file)

Specifications: Part (a):

Write a program in Java or C# that declares an array of 5 elements and displays the contents of the array. Your program should attempt to access the 6th element in the array (which does not exist) and using try.. catch your program should prevent the run-time error and display your error message to the user. Sample output including error message is provided below.

SAMPLE OUTPUT:

Part (a)

Printing an element out of bounds

5

7

11

3

0

You went out of limits in the array

Part (b): Define an exception class called InvalidTimeFormatException. If the user enters an invalid time like 1065 or 2515, the program should throw and handle an InvalidTimeFormatException. NOTE: Assume the user will enter the time as a 4-digit number with no colon.

SAMPLE OUTPUT:

Part (b)

Enter time in 24-hour notation:

1614

That is the same as 4:14 PM

Again? (y/n)

y

Enter time in 24-hour notation:

0245

That is the same as 2:45 AM

Again? (y/n)

y

Enter time in 24-hour notation:

1215

That is the same as 12:15 PM

Again? (y/n)

y

Enter time in 24-hour notation:

2612

Error: Hour can only be between 0 and 23

Again? (y/n)

y

Enter time in 24-hour notation:

1562

Error: Minutes can only be between 0 and 59

Again? (y/n)

n

Solutions

Expert Solution

a.

// IndexOutOfBoundsDemo.java : Java program to catch IndexOutOfBoundsException

public class IndexOutOfBoundsDemo {

   public static void main(String[] args)
   {

       // create an array of 5 integers
       int[] arr = {5, 7, 11, 3, 0};
       System.out.println("Printing an element out of bounds");

       // loop 6 times to try display an element at index beyond the array
       for(int i=0;i<6;i++)
       {
           try
           {
               System.out.println(arr[i]);
          
           }catch(IndexOutOfBoundsException e)
           {
               // this is executed when we try to access an element at index which is beyond the size of the array
               System.out.println("You went out of limits in the array.");
           }
       }
   }
}

//end of IndexOutOfBoundsDemo.java

Output:

b.

// InvalidTimeFormatException.java: Custom exception class which is thrown when an invalid time is encountered

public class InvalidTimeFormatException extends Exception
{
   // constructor that takes as input the exception message
   public InvalidTimeFormatException(String msg)
   {
       super(msg); // calls Exception constructor passing the message
   }
}

//end of InvalidTimeFormatException.java

// InvalidTimeExceptionDemo.java : Java program to catch InvalidTimeFormatException

import java.util.Scanner;

public class InvalidTimeExceptionDemo{

   public static void main(String[] args)
   {
       String choice;
       int time24, hour, minute;
       String tz;
       Scanner sc = new Scanner(System.in);
      
       // loop that continues till the user wants
       do
       {
           // input the time in 24 hour format as 4-digit number with no colon.
           System.out.println("Enter time in 24-hour notation: ");
           time24 = sc.nextInt();
          
           // extract the hour and minute from the input
           hour = time24/100;
           minute = time24%100;
          
           try {
               // invalid hour
               if(hour < 0 || hour > 23)
                   throw new InvalidTimeFormatException("Error: Hour can only be between 0 and 23");
               else if(minute < 0 || minute > 59) // invalid minute
                   throw new InvalidTimeFormatException("Error: Minutes can only be between 0 and 59");
               else
               {
                   // valid time, convert it to 12-hour format
                   if(hour >= 0 && hour < 12)
                   {
                       tz = "AM";
                       if(hour == 0)
                           hour = 12;
                   }else
                   {
                       tz = "PM";
                       if(hour > 12)
                           hour = hour-12;
                   }
                   // display the time in 12-hour format
                   System.out.println("That is the same as "+hour+":"+minute+" "+tz);
               }
           }catch(InvalidTimeFormatException e)
           {
               // executed when user entered time is invalid (hour/ minute)
               System.out.println(e.getMessage());
           }
          
           // ask if the user wants to input again
           System.out.println("Again? (y/n) ");
           choice = sc.next();
          
       }while(choice.equalsIgnoreCase("y"));
   }
}

//end of InvalidTimeExceptionDemo.java

Output:


Related Solutions

(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a  ...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to   be   thrown   when   a   string   is   discovered   that   has   too   many   characters   in   it. Consider   a   program   that   takes   in   the   last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,  ...
EXCEPTION HANDLING Concept Summary: 1. Exception handling 2. Class design Description Write a program that creates...
EXCEPTION HANDLING Concept Summary: 1. Exception handling 2. Class design Description Write a program that creates an exception class called ManyCharactersException, designed to be thrown when a string is discovered that has too many characters in it. Consider a program that takes in the last names of users. The driver class of the program reads the names (strings) from the user until the user enters "DONE". If a name is entered that has more than 20 characters, throw the exception....
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java...
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java * description of class Driver here. *these is the main class where it acts like parent class. Compiler will execute firstly static method. import java.util.Scanner; public class Driver {     public static void main (String[] args){         Scanner stdIn = new Scanner(System.in);         String user;         String computer;         char a = 'y';         do {             System.out.println("What kind of Computer would you like?");...
I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code...
I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code i have in POWERSHELL: while($true) { $input= Read-Host "Enter the option 1-5" if ($input -eq 5) { break } #B. Create a “switch” statement that continues to prompt a user by doing each of the following activities, until a user presses key 5: switch ( $input ){ #Using a regular expression, list files within the Requirements1 folder, with the .log file extension and redirect...
Raising an Exception In the previous problem, you used a try/except statement to catch an exception....
Raising an Exception In the previous problem, you used a try/except statement to catch an exception. This problem deals with the opposite situation: raising an exception in the first place. One common situation in which you will want to raise an exception is where you need to indicate that some precondition that your code relies upon has not been met. (You may also see the assert statement used for this purpose, but we won’t cover that here.) Write a function...
What is Try and Catch in Java with example?
What is Try and Catch in Java with example?
What advantages does object-oriented exception handling provide? When a program contains multiple catch blocks, how are...
What advantages does object-oriented exception handling provide? When a program contains multiple catch blocks, how are they handled? Write the statement to declare a three-by-four array of integers with the elements initialized to zero. Name the array myArray. What is the difference between volatile and nonvolatile storage in Java programming? Give examples of different storage situations. What are some of the advantages of the ArrayList class over the Arrays class? How can you use the enhanced for loop? What does...
Java try and catch problem public void method1(){ int[] array = new int[1]; try{ array[2] =...
Java try and catch problem public void method1(){ int[] array = new int[1]; try{ array[2] = 0;} catch(ArithmeticException e){array[2] = 0} // ? finally{ return 0;}} Could you please tell me why the line with the question mark will not report an error?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT