0.) Display the following menu to the user: System.out.println(\"What is the typ
ID: 3597423 • Letter: 0
Question
0.) Display the following menu to the user:
System.out.println("What is the type of file that you wish to read?");
System.out.println("1. Good file");
System.out.println("2. Too few recs in the counter (more recs than anticipated.)");
System.out.println("3. Too many recs in the counter (less recs than anticipated");
System.out.println("4. Non-numeric record counter.");
System.out.println("5. Invalid data in record – ex.: GPA non-numeric");
System.out.println("6. Invalid file name.");
Note: Each file must contain an int at the beginning, stating the number of records in the file. Afterwards, the number of records in the file will follow. Each record that follows will consist of a last name (String), and a gpa (double). However, to test the error handling of your program, the number of records will not always match the int value. All possible combinations should be tested.
1.) Prompt the user for menu option, relating to the file the program will input to test error handling logic.
2.) From the int value at the beginning of the file, create a 1-D array of Student objects, with the size of the int value. The student object consists of a String with lastName and a double with gpa.
3.) Load all the Student objects onto the array.
4.) Calculate the lowest, highest, sum, and average of all the gpa’s (doubles) in the array.
5.) Print out all the statistics:
a.) The student with the lowest gpa is: xyz with gpa of: ###
b.) The student with the highest gpa is: abc with gpa of: ###
c.) The average of all students’ gpa is: ###
6.) Include exception handling as follows:
In main method:
Put try-catch block inside a tryAgain Loop, and catch the exceptions that were thrown by the 3 methods called in the try block (getUserInput, processFile and summarizeResults)
a.) FileNotFoundException (retry)
b.) InputMismatchException (no retry)
c.) BadDataException (no retry)
d.) NoSuchElementException (no retry)
e.) Exception (no retry)
In the getUserInput method:
Put try-catch block for entering a valid menu option:
a.) InputMismatchException (retry with loop locally)
In processFile method:
Put try-catch block and catch the exceptions possible. Some can be handled here, but most are thrown back to main for handling:
a.) InputMismatchException – a non-numeric value found in the gpa field of one of the records
Option 1: throw error back to main method to handle, end program
Option 2: handle error locally by skipping bad record (array will not be filled up)
b.) FileNotFoundException - thrown back to main
c.) BadDataException - actualNumRecs > numRecs stated in file - throw back to main
d.) NoSuchElementException - when a record does not have any gpa field - throw back to main
e.) Exception - for everything else - go back to main
f.) Include a finally clause to close the file
In summarizeResults method:
Put try-catch block outside, to catch IndexOutOfBoundsException, or InputMismatchException.
Inside try-block, iterate through the array of values, sum them, and compare to see
which is smaller and which is larger.
After iterating through array, report on average of gpa’s, smallest gpa, and largest gpa.
The only problem that you may want to catch is if you try to process a null entry in the array, because you skipped a bad record in the processFile() method.
7.) (Given to you already!) Create a new class, BadDataException which extends RuntimeException or Exception class. The class is composed of a default constructor, and an overloaded constructor that receives a String message. That constructor calls the super(message) constructor, passing it the String message.
8.) In the comments, list the names of the files that will fulfill each test case, to go through all the possible errors in the program. For example:
a.) abc.txt file name that doesn't exist.
b.) xyz.txt file has bad data in it (i.e. letters instead of numbers)
c.) lmn.txt file is empty
d.) ijk.txt file has valid data
9.) (Given to you already!) In the Project folder, provide a file for each of the test cases displayed by the menu.
ErrorHandlingExample.java
package errorhandlingexample;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
*
* @author mtsguest
*/
public class ErrorHandlingExample {
//Define a global array of Student objects, but don't instantiate it until the getUserInput() method.
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
boolean tryAgain = true;
int menuItemSelected = 0;
ErrorHandlingExample errorHandle1 = new ErrorHandlingExample();
while (tryAgain)
{
try
{
menuItemSelected = errorHandle1.getUserInput();
errorHandle1.processFile(menuItemSelected);
errorHandle1.summarizeResults();
tryAgain = false;
}
catch (FileNotFoundException e)
{
tryAgain = true;
System.out.println(e.getMessage());
}
catch (InputMismatchException e)
{
tryAgain = false;
System.out.println(e.getMessage());
}
catch (BadDataException e)
{
tryAgain = false;
System.out.println(e.getMessage());
}
catch (NoSuchElementException e)
{
tryAgain = false;
System.out.println(e.getMessage());
}
catch (Exception e)
{
tryAgain = false;
System.out.println(e.getMessage());
}
}
}
public int getUserInput()
{
boolean validMenu = false;
int usersChoice = 0;
Scanner keyboard = new Scanner(System.in);
while (!validMenu)
{
try
{
displayMenu();
usersChoice = keyboard.nextInt();
if (usersChoice < 1 || usersChoice > 6)
{
System.out.println("Your selection is invalid. Enter 1 - 6.");
validMenu = false;
}
else
{
validMenu = true;
}
}
catch(InputMismatchException e)
{
validMenu = false;
keyboard.nextLine();
System.out.println("Incorrect menu selection.");
}
}
return usersChoice;
}
public void processFile(int usersChoice) throws FileNotFoundException
{
int numRecs;
String fileName;
String badData1 = "goodFile.txt";
String badData2 = "tooFewRecs.txt";
String badData3 = "tooManyRecs.txt";
String badData4 = "nonNumericRecCounter.txt";
String badData5 = "invalidData.txt";
String badData6 = "xyz.txt";
switch (usersChoice)
{
case 1:
fileName = badData1;
break;
case 2:
fileName = badData2;
break;
case 3:
fileName = badData3;
break;
case 4:
fileName = badData4;
break;
case 5:
fileName = badData5;
break;
case 6:
fileName = badData6;
break;
default:
fileName = badData1;
}
try
{
File aFile = new File(fileName);
Scanner myFile = new Scanner(aFile);
numRecs = myFile.nextInt();
//This is where you instantiate the array of Student objects, and
//where you use a counter loop, using numRecs as number of time to loop,
//to read all the records in the input file, and
//create a Student object per record, to place in the global array of Student objects
//You can do these steps either right here, or by calling a method that does them.
//When this method successfully ends, the array of Student objects should be populated.
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("The file " + fileName + " was not found.");
}
catch (InputMismatchException e)
{
}
catch (BadDataException e)
{
//You can report on the bad data, and skip the bad record, so you can process the rest of the records.
throw new BadDataException("bad data");
}
catch (NoSuchElementException e)
{
}
catch (Exception e)
{
}
//missing finally
}
public void displayMenu()
{
System.out.println("What type of file do you wish to read?");
System.out.println("1. Good File");
System.out.println("2. Too few recs in the counter (more recs than anticipated");
System.out.println("3. Too many recs in the counter (less recs than anticipated");
System.out.println("4. Non-numeric record counter");
System.out.println("5. Invalid data in record - ex. GPA non-numeric");
System.out.println("6. Invalid file name");
}
public void summarizeResults()
{
//This is where you use the array of Student objects you created, and you
//loop through it, finding the student with the highest gpa, the lowest gpa, and then
//accumulate all the gpas, so that at the end of the loop, you can calculate the average gpa.
//You can optionally put try catch for the arrayOutOfBounds error.
//By now, the data in the array should be valid, since any errors were caught in the processFile method
//You should have skipped the bad data recs.
//If you skipped a bad data record, you could have an array with empty elements. Thus,
//you could have exceptions if you don't first check that the element is not equal to nulls.
}
}
Student.java
package errorhandlingexample;
/**
*
* @author mtsguest
*/
public class Student {
private String lastName;
private double gpa;
public Student(String ln, double aGPA)
{
lastName = ln;
gpa = aGPA;
}
public String getLastName() {
return lastName;
}
public double getGpa() {
return gpa;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
@Override
public String toString() {
return "Student{" + "lastName=" + lastName + ", gpa=" + gpa + '}';
}
}
BadDataException.java
package errorhandlingexample;
/**
*
* @author mtsguest
*/
public class BadDataException extends RuntimeException {
public BadDataException()
{
super();
}
public BadDataException(String message)
{
super(message);
}
}
goodFile.txt
3
Smith 3.4
Molina 4.3
Iglesias 3.2
tooFewRecs.txt
4
Charters 3.98
Cartacio 4.3
tooManyRecs.txt
1
Cartacio 4.3
Fernandez 3.1
nonNumericRecCounter.txt
j
Charters 3.98
invalidData.txt
3
Jones 3.4
Smith abc
Hernandez 3.98
xyz.txt (Does not exist)
Explanation / Answer
ErrorHandlingExample .java
package errorhandlingexample;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
*
* @author mtsguest
*/
public class ErrorHandlingExample {
Student[] st;
//Define a global array of Student objects, but don't instantiate it until the getUserInput() method.
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
boolean tryAgain = true;
int menuItemSelected = 0;
ErrorHandlingExample errorHandle1 = new ErrorHandlingExample();
while (tryAgain)
{
try
{
menuItemSelected = errorHandle1.getUserInput();
errorHandle1.processFile(menuItemSelected);
errorHandle1.summarizeResults();
tryAgain = false;
}
catch (FileNotFoundException e)
{
tryAgain = true;
System.out.println(e.getMessage());
}
catch (InputMismatchException e)
{
tryAgain = false;
System.out.println(e.getMessage());
}
catch (BadDataException e)
{
tryAgain = false;
System.out.println(e.getMessage());
}
catch (NoSuchElementException e)
{
tryAgain = false;
System.out.println(e.getMessage());
}
catch (Exception e)
{
tryAgain = false;
System.out.println(e.getMessage());
}
}
}
public int getUserInput()
{
boolean validMenu = false;
int usersChoice = 0;
Scanner keyboard = new Scanner(System.in);
while (!validMenu)
{
try
{
displayMenu();
usersChoice = keyboard.nextInt();
if (usersChoice < 1 || usersChoice > 6)
{
System.out.println("Your selection is invalid. Enter 1 - 6.");
validMenu = false;
}
else
{
validMenu = true;
}
}
catch(InputMismatchException e)
{
validMenu = false;
keyboard.nextLine();
System.out.println("Incorrect menu selection.");
}
}
return usersChoice;
}
public void processFile(int usersChoice) throws FileNotFoundException
{
int numRecs;
String fileName;
String badData1 = "goodFile.txt";
String badData2 = "tooFewRecs.txt";
String badData3 = "tooManyRecs.txt";
String badData4 = "nonNumericRecCounter.txt";
String badData5 = "invalidData.txt";
String badData6 = "xyz.txt";
switch (usersChoice)
{
case 1:
fileName = badData1;
break;
case 2:
fileName = badData2;
break;
case 3:
fileName = badData3;
break;
case 4:
fileName = badData4;
break;
case 5:
fileName = badData5;
break;
case 6:
fileName = badData6;
break;
default:
fileName = badData1;
}
try
{
File aFile = new File(fileName);
if(!aFile.exists())
throw new FileNotFoundException();
Scanner myFile = new Scanner(aFile);
numRecs = Integer.parseInt(myFile.nextLine());
st=new Student[numRecs];
String record;
String[] token;
Student student;
int i;
for ( i= 0; i < numRecs; i++) {
try{
record=myFile.nextLine();
token=record.split(" ");
student=new Student(token[0], Double.parseDouble(token[1]));
st[i]=student;
}catch(Exception ne){
throw new BadDataException("Bad data");
}
}
//This is where you instantiate the array of Student objects, and
//where you use a counter loop, using numRecs as number of time to loop,
//to read all the records in the input file, and
//create a Student object per record, to place in the global array of Student objects
//You can do these steps either right here, or by calling a method that does them.
//When this method successfully ends, the array of Student objects should be populated.
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("The file " + fileName + " was not found.");
}
catch (InputMismatchException e)
{
}
catch (BadDataException e)
{
//You can report on the bad data, and skip the bad record, so you can process the rest of the records.
throw new BadDataException("bad data");
}
catch (NoSuchElementException e)
{
}
catch (Exception e)
{
System.out.println(e);
throw e;
}
//missing finally
}
public void displayMenu()
{
System.out.println("What type of file do you wish to read?");
System.out.println("1. Good File");
System.out.println("2. Too few recs in the counter (more recs than anticipated");
System.out.println("3. Too many recs in the counter (less recs than anticipated");
System.out.println("4. Non-numeric record counter");
System.out.println("5. Invalid data in record - ex. GPA non-numeric");
System.out.println("6. Invalid file name");
}
public void summarizeResults()
{
double total=0.0d;
double lowGpa = 0;
double highGpa=0;
String lowLastName=null;
String highLastName=null;
boolean isFirstValidRec=true;
int n=0;
double gpa;
String name;
try{
for (int i = 0; i < st.length; i++) {
if(st[i]!=null){
gpa=st[i].getGpa();
name=st[i].getLastName();
if(isFirstValidRec){
lowGpa=gpa;
highGpa=gpa;
lowLastName=name;
highLastName=name;
isFirstValidRec=false;
}else{
if(highGpa<gpa){
highGpa=gpa;
highLastName=name;
}
if(gpa<lowGpa){
lowGpa=gpa;
lowLastName=name;
}
}
total+=st[i].getGpa();
n++;
}
}
double avg=(double)total/n;
System.out.println("The student with the lowest gpa is: "+ lowLastName + "with gpa of: "+lowGpa);
System.out.println("The student with the highest gpa is: "+ highLastName + "with gpa of: "+highGpa);
System.out.println("The average of all students’ gpa is: "+ avg);
}catch(Exception ex){
throw ex;
}
//This is where you use the array of Student objects you created, and you
//loop through it, finding the student with the highest gpa, the lowest gpa, and then
//accumulate all the gpas, so that at the end of the loop, you can calculate the average gpa.
//You can optionally put try catch for the arrayOutOfBounds error.
//By now, the data in the array should be valid, since any errors were caught in the processFile method
//You should have skipped the bad data recs.
//If you skipped a bad data record, you could have an array with empty elements. Thus,
//you could have exceptions if you don't first check that the element is not equal to nulls.
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.