Question

PLEASE CODE IN C# NOT in Java EXCEPTION HANDLING Concept Summary: Use of try... catch in...

PLEASE CODE IN C# NOT 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#. 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 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

Homework Answers

Answer #1
// IndexOutOfBoundsDemo.cpp

export module snippet;

import <string>;
import <vector>;
import <iostream>;
import <stdexcept>;


export class IndexOutOfBoundsDemo
{

   static void main(std::vector<std::wstring> &args)
   {

           // create an array of 5 integers
           std::vector<int> arr = {5, 7, 11, 3, 0};
           std::wcout << L"Printing an element out of bounds" << std::endl;

           // loop 6 times to try display an element at index beyond the array
           for (int i = 0;i < 6;i++)
           {
                   try
                   {
                           std::wcout << arr[i] << std::endl;

                   }
                   catch (const std::out_of_range &e)
                   {
                           // this is executed when we try to access an element at index which is beyond the size of the array
                           std::wcout << L"You went out of limits in the array." << std::endl;
                   }
           }
   }
};

//end of IndexOutOfBoundsDemo.cpp

OUTPUT:

// InvalidTimeFormatException.cpp
export module snippet;

import <string>;
import <vector>;
import <iostream>;
import <stdexcept>;



export class InvalidTimeFormatException : public std::runtime_error
{
   // constructor that takes as input the exception message
   public:
   InvalidTimeFormatException(const std::wstring &msg) : Exception(msg) // calls Exception constructor passing the message
   {
   }
};

//end of InvalidTimeFormatException.cpp

// InvalidTimeExceptionDemo.cpp

export class InvalidTimeExceptionDemo
{

   static void main(std::vector<std::wstring> &args)
   {
           std::wstring choice;
           int time24, hour, minute;
           std::wstring 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.
                   std::wcout << L"Enter time in 24-hour notation: " << std::endl;
                   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)
                           {
                                   delete sc;
                                   throw InvalidTimeFormatException(L"Error: Hour can only be between 0 and 23");
                           }
                           else if (minute < 0 || minute > 59) // invalid minute
                           {
                                   delete sc;
                                   throw InvalidTimeFormatException(L"Error: Minutes can only be between 0 and 59");
                           }
                           else
                           {
                                   // valid time, convert it to 12-hour format
                                   if (hour >= 0 && hour < 12)
                                   {
                                           tz = L"AM";
                                           if (hour == 0)
                                           {
                                                   hour = 12;
                                           }
                                   }
                                   else
                                   {
                                           tz = L"PM";
                                           if (hour > 12)
                                           {
                                                   hour = hour - 12;
                                           }
                                   }
                                   // display the time in 12-hour format
                                   std::wcout << L"That is the same as " << hour << L":" << minute << L" " << tz << std::endl;
                           }
                   }
                   catch (const InvalidTimeFormatException &e)
                   {
                           // executed when user entered time is invalid (hour/ minute)
                           std::wcout << e->what() << std::endl;
                   }

                   // ask if the user wants to input again
                   std::wcout << L"Again? (y/n) " << std::endl;
                   choice = sc->next();


           }while (choice.equalsIgnoreCase(L"y"));

           delete sc;
   }
};

//end of InvalidTimeExceptionDemo.cpp

OUTPUT:

THUMBS UP IF YOU LIKE IT !

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
In JAVA For practice using exceptions, this exercise will use a try/catch block to validate integer...
In JAVA For practice using exceptions, this exercise will use a try/catch block to validate integer input from a user. Write a brief program to test the user input. Use a try/catch block, request user entry of an integer, use Scanner to read the input, throw an InputMismatchException if the input is not valid, and display "This is an invalid entry, please enter an integer" when an exception is thrown. InputMismatchException is one of the existing Java exceptions thrown by...
Write a java program that creates an integer array with 50 random values, prompts the user...
Write a java program that creates an integer array with 50 random values, prompts the user to enter the index of an element in the array between 0 and 49, then displays the corresponding element value. If the specified index is out of bounds, display an error message (e.g. “Out of Bounds”) and ask the user to enter another index. Use a while loop that will keep prompting the user until a valid input is received. To handle invalid inputs,...
Complete Programming Assignment Chapter 10. Use program In JAVA ProductCodes.java on pages 446-447, it will provide...
Complete Programming Assignment Chapter 10. Use program In JAVA ProductCodes.java on pages 446-447, it will provide you most of the needed code. You are to design and implement a program that reads a series of 10 integers from user and print the average. Read each integer as a string and convert to integer using Integer.parseInt method. If this process throws a NumberFormatException (not a valid number), catch and handle the exception by printing an error message "Not a valid entry,...
Write a C++ program that converts time of day from a 24-hour notation to a 12-hour...
Write a C++ program that converts time of day from a 24-hour notation to a 12-hour notation. For example, it should convert 14:25 to 2:25 PM. (A) The user provides input as two integers separated by ‘:’. The following function prototype should capture the user inputs as described below: void input(int& hours24, int& minutes); //Precondition: input(hours, minutes) is called with //arguments capable of being assigned values. //Postcondition: // user is prompted for time in 24 hour format: // HH:MM, where...
WITH JAVA Follow the instructions in the attached to complete Task#2 and submit work along with...
WITH JAVA Follow the instructions in the attached to complete Task#2 and submit work along with screenshots of your output. I have attached the class code for Task#1 that you can use while completing Task#2. Task#1 CODE /** SocSecException exception class */ public class SocSecException extends Exception { public SocSecException(String error) { super("Invalid the social security number, " + error); } } Task #2 Writing Code to Handle an Exception 1. In the main method: a. The main method should...
I need this before the end of the day please :) In Java 10.13 Lab 10...
I need this before the end of the day please :) In Java 10.13 Lab 10 Lab 10 This program reads times of runners in a race from a file and puts them into an array. It then displays how many people ran the race, it lists all of the times, and if finds the average time and the fastest time. In BlueJ create a project called Lab10 Create a class called Main Delete what is in the class you...
I need the java code for a 4-function calculator app on android studio. Please make sure...
I need the java code for a 4-function calculator app on android studio. Please make sure all the requirements shown below are followed (such as the error portion and etc). The topic of this app is to simply create a 4 function calculator which calculates math expressions (add, subtract, multiply, and divide numbers). The requirements are the following : - The only buttons needed are 0-9, *, /, +, -, a clear, and enter button - Implement the onclicklistener on...
I am to create three different versions of the following C program code below that implements...
I am to create three different versions of the following C program code below that implements the conversion of unsigned binary numbers into decimal (Base 2 to Base 10 conversion). Version 1: Complete the C program ”bin2dec ver1.c” that implements binary to decimal conversion. The maximum number of binary bits is 32. The program is made of the functions ”unsigned binary to decimal(const char *str)”and ”main”. The parameter ”str” passed to this function points to a C string comprising only...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code to initialize the CustomerAccountsDB database table and add a set of customer accounts is provided. Finish the code in these 3 methods in CustomerAccountDB.java to update or query the database: -purchase(double amountOfPurchase) -payment(double amountOfPayment) -getCustomerName() Hint: For getCustomerName(), look at the getAccountBalance() method to see an example of querying data from the database. For the purchase() and payment() methods, look at the addCustomerAccount() method...
This is a Java program Program Description You work for a local cell phone company and...
This is a Java program Program Description You work for a local cell phone company and have been asked to write a program to calculate the price of a cell phone data plan being purchased by a customer. The program should do the following tasks: Display a menu of the data plans that are available to be purchased. Read in the user’s selection from the menu.  Input Validation: If the user enters an invalid option, the program should display an error...