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 a
ays
· 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 a
ay.
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 e
or 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 a
ay
Fill in the method saveToMultidimensionalA
ay(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 a
ay will have 10 rows and 7 columns.
Each line in the file looks something like this:
XXXXXXXXXX,Thursday,72,56,40
Each line in the file will be written into a single element in the multi-dimensional a
ay.
It will be your job to use a nested loop to loop through the a
ay 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 a
ay "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 a
ay, we have to make sure we have numbers for the day and week that are valid within the bounds of the a
ay.
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 a
ay.
Throw exception for invalid week numbe
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 numbe
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 e
or 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: XXXXXXXXXX01Day 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 a
ay of lines
DO NOT MODIFY THIS METHOD
public static String[] removeCSVHeader(String[] originalA
ay){
XXXXXXXXXXString[] newA
ay = new String[originalA
ay.length - 1];
XXXXXXXXXXfor (int i = 0, j = 0; i < originalA
ay.length; i++) {
XXXXXXXXXXif (i != 0) {
XXXXXXXXXXnewA
ay[j++] = originalA
ay[i];
}
}
XXXXXXXXXXreturn newA
ay;
}
public static String readCSVLines(String filename) throws IOException{
read in the file and return its contents
XXXXXXXXXXreturn "";
}
public static String[][] saveToMultidimensionalA
ay(String csvContent, int numRows, int numColumns){
XXXXXXXXXXString[] csvLines = csvContent.split("\n");
XXXXXXXXXXString[] csvDataWithoutHeaders = removeCSVHeader(csvLines);
create a multidimensional a
ay with numRows rows and numColumns columns
use a nested loop to loop through each line of the CSV to put in the multidimensional a
ay
return the multidimensional a
ay
XXXXXXXXXXreturn new String[][]{};
}
public static String getWeekToSelectFromData(Scanner scanner){
XXXXXXXXXXSystem.out.print("Enter a week number between 1 and 10 with information you want: ");
XXXXXXXXXXString weekToSelect = scanner.nextLine();
XXXXXXXXXXreturn weekToSelect;
}
public static String getDayToSelectFromData(Scanner scanner){
XXXXXXXXXXSystem.out.print("Enter a day number between 1 and 7 with information you want: ");
XXXXXXXXXXString dayToSelect = scanner.nextLine();
XXXXXXXXXXreturn dayToSelect;
}
public static void main(String[] args) throws IOException {
XXXXXXXXXXString csvContent = readCSVLines(INPUT_FILENAME);
XXXXXXXXXXString[][] csvData = saveToMultidimensionalA
ay(csvContent, 10, 7);
XXXXXXXXXXScanner scanner = new Scanner(System.in);
XXXXXXXXXXString weekToSelect;
XXXXXXXXXXint weekNumberToSelect = 0;
XXXXXXXXXXString dayToSelect;
XXXXXXXXXXint dayNumberToSelect = 0;
XXXXXXXXXXString integerExceptionDayOfWeekMessage = "You have to enter an integer for the day!";
XXXXXXXXXXString integerExceptionWeekMessage = "You have to enter an integer for the week!";
XXXXXXXXXXString invalidNumberExceptionDayOfWeekMessage = "You need to enter a number between 1 and 7 for the day!";
XXXXXXXXXXString invalidNumberExceptionWeekMessage = "You need to enter a number between 1 and 10 for the week!";
do not change code in main() above this line
XXXXXXXXXXdo {
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
XXXXXXXXXXweekToSelect = getWeekToSelectFromData(scanner);
XXXXXXXXXXweekNumberToSelect = 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.
XXXXXXXXXXdo {
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
XXXXXXXXXXdayToSelect = getDayToSelectFromData(scanner);
XXXXXXXXXXdayNumberToSelect = 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 invalidNumberExceptionDayOfWeekMessage.
do not change code in main() below this line
XXXXXXXXXXString specificDayInfo = csvData[weekNumberToSelect - 1][dayNumberToSelect - 1];
XXXXXXXXXXString[] dayInfoA
ay = specificDayInfo.split(",");
XXXXXXXXXXSystem.out.println("Date: " + dayInfoA
ay[0].strip());
XXXXXXXXXXSystem.out.println("Day Of Week: " + dayInfoA
ay[1].strip());
XXXXXXXXXXSystem.out.println("High temperature (degrees F): " + dayInfoA
ay[2].strip());
XXXXXXXXXXSystem.out.println("Low temperature (degrees F): " + dayInfoA
ay[4].strip());