Throwing and reporting exceptions

105 views 7:56 am 0 Comments March 31, 2023

Topics Covered: · Exception class · Throwing and reporting exceptions · Handling exceptions with try/catch statements · Creating custom exceptions · Reading from files This assessment will assess your mastery of the following Learning Outcomes: · Reading data from CSV files · Saving data to multi-dimensional arrays · Catching and handling exceptions in your code · Implementing code that throws an exception when input is invalid · Using exceptions to communicate with other programmers Assignment Open the activity and clone it to your computer. You will be reading a CSV file called “austin_weather.csv” containing weather data from Austin, Texas for ten weeks between December 2013 and March 2014 into a multi-dimensional array. A user of the program will enter two numbers for which week and which day of the week they want weather data, then the program will fetch that data based on the numbers provided for the week and the day of the week based on the inputs. Class Diagram – Weather Data Application This UML diagram shows the overall solution design: · You will be adding code to the methods in the Application class with a star ( * ) in the UML class diagram. The other methods have been completely coded in the starter code for the project. Step One – Create the custom exception classes There will be two custom exceptions that will need to be created in the repository, InvalidWeekException and InvalidDayOfWeekException. Each of these will pass in a root error from IllegalArgumentException. Remember, for each class, you will need to write a constructor that takes in a message as well as a Throwable argument. Step Two – Read from file Fill in the method readCSVLines(String filename) to get data from the CSV file and return a String with its contents. Step Three – Read the lines into a 2D array Fill in the method saveToMultidimensionalArray(String csvData, int numRows, int numColumns)) that takes in a String for the result from readCSVLines() and returns a String[][] value. The CSV file will have ten weeks of data, and there are seven days a week, so the 2D String array will have 10 rows and 7 columns. Each line in the file looks something like this: 2014-01-16,Thursday,72,56,40 Each line in the file will be written into a single element in the multi-dimensional array. It will be your job to use a nested loop to loop through the array using a counter to keep track of the day and the week. You can assume the first entry will be at index [0][0] and the last entry will be at index [9][6]. The final multi-dimensional array “looks” like this: Step Four – Wrap the code inside the do-while loops in try/catch blocks We attempt to get user input inside of the do-part of the do-while loops because if the user enters an invalid input, we want to be able to keep prompting them until they enter a valid input. Therefore, we will need to catch any exceptions created from attempting to get data for the week and the day from the user. To figure out what exception you need to catch, execute the program and attempt to put in a string input. When the program fails, look at which exception is thrown in your output so you can catch that exception. When you catch the exception, instead of printing the exception’s message, you can instead print the variables integerExceptionWeekMessage and integerExceptionDayOfWeekMessage for each of the do-while loops, depending on whether you’re attempting to get week or day of week from the user. Step Five – Throw custom exceptions for invalid input Before we attempt to retrieve data from the multi-dimensional array, we have to make sure we have numbers for the day and week that are valid within the bounds of the array. We want to create two try/catch blocks, one for the week number and another for the day of week number. In each catch block, we want to print the message received from the exception and then exit the program without crashing. We don’t want the program to continue running after we’ve received an invalid week or day of week when the input is a number outside the bounds of our multidimensional array. Throw exception for invalid week number We will want to check if the week number is less than 1 or greater than 10. Even though the indices for the weeks will be 0 through 9, we are asking for 1 through 10 from the user so that we can provide a more natural user experience. If the number entered for the week is greater than 10 or less than 1, we want to throw an InvalidWeekException. For the message, we will pass it in from the variable invalidNumberExceptionWeekMessage created above. Throw exception for invalid day of week number We will want to check if the day of week number is less than 1 or greater than 7. Even though the indices for the days of the week will be 0 through 6, we are asking for 1 through 7 from the user so that we can provide a more natural user experience. If the number entered for the week is greater than 7 or less than 1, we want to throw an InvalidDayWeekException. For the message, we will pass it in from the variable invalidNumberExceptionDayOfWeekMessage created above. Test your code Unit tests have been provided in the ApplicationTest.java file. Make sure your code passes the tests defined there as you complete the remaining steps. After the unit tests pass and after you have completed all five steps of the assignment, run the program with invalid number inputs for week and for day of week. First attempt to test by entering a string, then test by entering a number outside of the valid bounds. Once those invalid inputs print the error messages and do the following: · Re-prompt for input if a non-integer value is entered for week or day of week · Exit the program gracefully, without crashing, if the week or day of week are outside of expected bounds Then run the program with valid day and week numbers and ensure you get weather data back. When you are finished, the final code should execute like this: # Attempt 1Enter a week number between 1 and 10 with information you want: applesYou have to enter an integer for the week!Enter a week number between 1 and 10 with information you want: 14You need to enter a number between 1 and 10 for the week!# Attempt 2Enter a week number between 1 and 10 with information you want: 10Enter a day number between 1 and 7 with information you want: applesYou have to enter an integer for the day!Enter a day number between 1 and 7 with information you want: 14You need to enter a number between 1 and 7 for the day!# Attempt 3Enter a week number between 1 and 10 with information you want: 10Enter a day number between 1 and 7 with information you want: 7Date: 2014-03-01Day Of Week: SaturdayHigh temperature (degrees F): 82Low temperature (degrees F): 68Average temperature (degrees F): 53 ? Reflection Each activity, we’ll try to give you something a little extra to think about. Write a short response to this question: If we did not know how many weeks of data we had in the CSV file, how could we figure that out in our code? You don’t have to write any actual code, just write the thought process. I use IntelliJ IDE this is how this is how it shows on IntelliJ package com.kenzie.app; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.InputMismatchException; import java.util.Scanner; // create custom exceptions InvalidWeekException and InvalidDayOfWeekException first public class Application { static final String INPUT_FILENAME = “austin_weather.csv”; // removes the CSV header from the array of lines // DO NOT MODIFY THIS METHOD public static String[] removeCSVHeader(String[] originalArray){ String[] newArray = new String[originalArray.length – 1]; for (int i = 0, j = 0; i < originalarray.length; i++) { if (i != 0) { newarray[j++] = originalarray[i]; } } return newarray; } public static string readcsvlines(string filename) throws ioexception{ // read in the file and return its contents return “”; } public static string[][] savetomultidimensionalarray(string csvcontent, int numrows, int numcolumns){ string[] csvlines = csvcontent.split(“n”); string[] csvdatawithoutheaders = removecsvheader(csvlines); // create a multidimensional array with numrows rows and numcolumns columns // use a nested loop to loop through each line of the csv to put in the multidimensional array // return the multidimensional array return new string[][]{}; } public static string getweektoselectfromdata(scanner scanner){ system.out.print(“enter a week number between 1 and 10 with information you want: “); string weektoselect = scanner.nextline(); return weektoselect; } public static string getdaytoselectfromdata(scanner scanner){ system.out.print(“enter a day number between 1 and 7 with information you want: “); string daytoselect = scanner.nextline(); return daytoselect; } public static void main(string[] args) throws ioexception { string csvcontent = readcsvlines(input_filename); string[][] csvdata = savetomultidimensionalarray(csvcontent, 10, 7); scanner scanner = new scanner(system.in); string weektoselect; int weeknumbertoselect = 0; string daytoselect; int daynumbertoselect = 0; string integerexceptiondayofweekmessage = “you have to enter an integer for the day!”; string integerexceptionweekmessage = “you have to enter an integer for the week!”; string invalidnumberexceptiondayofweekmessage = “you need to enter a number between 1 and 7 for the day!”; string invalidnumberexceptionweekmessage = “you need to enter a number between 1 and 10 for the week!”; // do not change code in main() above this line do { // todo: wrap the code inside the do-part of the do-while loop with a try/catch block // when the exception is caught, print the message from variable integerexceptionweekmessage above weektoselect = getweektoselectfromdata(scanner); weeknumbertoselect = integer.parseint(weektoselect); } while(weeknumbertoselect == 0); // todo: throw an invalidweekexception if the week entered is greater than 10 or less than 1. // use a try/catch block here to catch the exception and print the message before adding an empty return statement. // when throwing the exception, pass in the message from variable invalidnumberexceptionweekmessage. do { // todo: wrap the code inside the do-part of the do-while loop with a try/catch block // when the exception is caught, print the message from variable integerexceptiondayofweekmessage above daytoselect = getdaytoselectfromdata(scanner); daynumbertoselect = integer.parseint(daytoselect); } while(daynumbertoselect == 0); // todo: throw an invaliddayofweekexception if the day of week entered is greater than 7 or less than 1. // use a try/catch block here to catch the exception and print the message before adding an empty return statement. // when throwing the exception, pass in the message from variable