Question

Please provide the full code...the skeleton is down below: Note: Each file must contain an int...

Please provide the full code...the skeleton is down below:

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 2 methods called in the try block (processFile and summarizeResults)

a.) FileNotFoundException (retry)
b.) InputMismatchException (no retry)
c.) BadDataException (no retry)
d.) NoSuchElementException (no retry)
e.) Exception (no retry)

In processFile method:

put try-catch block inside a do-loop, and catch the exceptions possible. Some can be handled here, but most are thrown back to main for handling:

a.) InputMismatchException - handled locally - non-numeric menu item selected
b.) FileNotFoundException - thrown back to main
c.) InputMismatchException - first num in file not numeric
- throw back to main

d.) BadDataException - actualNumRecs > numRecs stated in file - throw back to main
e.) InputMismatchException - second num in record is not a double - throw back to main
f.) NoSuchElementException - when a record does not have a gpa field - throw back to main
g.) Exception - for everything else - go back to main
h.)   Include a finally clause to close the file


In summarizeResults method:

put try-catch block outside, for-loop inside try
a.) catch Exception - throw back to main

7.) 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.) In the Project folder, provide a file for each of the test cases displayed by the menu.

Skeleton

package errorhandlingexample;

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;
}

public String toString() {

return "Student{" + "lastName=" + lastName + ", gpa=" + gpa + '}';
}
  }

package errorhandlingexample;

/**
*
* @author mtsguest
*/
public class BadDataException extends RuntimeException {
  
public BadDataException()
{
super();
}
public BadDataException(String message)
{
super(message);
}
  }

package errorhandlingexample;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class ErrorHandlingExample {

public static void main(String[] args) {
boolean tryAgain = true;
ErrorHandlingExample errorHandle1 = new ErrorHandlingExample();
while (tryAgain)
{
try
{
errorHandle1.processFile();
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 void processFile() throws FileNotFoundException
{
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
{
actualFileProcess(usersChoice);
validMenu = true;
}
  
}
catch(InputMismatchException e)
{
validMenu = false;
keyboard.nextLine();
System.out.println("Incorrect menu selection.");
}
}
}
public void actualFileProcess(int usersChoice) throws FileNotFoundException
{
String fileName;
String badData1 = "goodFile.txt";
String badData2 = "tooFewRecs.txt";
String badData3 = "tooManyRecs.txt";
String badData4 = "nonNumericsRecCounter.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);


}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("The file " + fileName + " was not found.");
//System.out.println("WROng!");
}
catch (InputMismatchException e)
{

}
catch (BadDataException e)
{
  
}
catch (NoSuchElementException e)
{

}
catch (Exception e)
{

}
}   
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()
{
  
}
  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

package errorhandlingexample;

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;
}

public String toString() {
return lastName + "with gpa of " + gpa + ".";
}
}

package errorhandlingexample;

/**
*
* @author mtsguest
*/
public class BadDataException extends RuntimeException {

public BadDataException() {
super();
}

public BadDataException(String message) {
super(message);
}
}

package errorhandlingexample;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class ErrorHandlingExample {

File aFile;
Scanner myfile;

public static void main(String[] args) {
boolean tryAgain = true;
ErrorHandlingExample errorHandle1 = new ErrorHandlingExample();
while (tryAgain) {
try {
errorHandle1.processFile();
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 void processFile() throws FileNotFoundException {
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 {
actualFileProcess(usersChoice);
validMenu = true;
}

} catch (InputMismatchException e) {
validMenu = false;
keyboard.nextLine();
System.out.println("Incorrect menu selection.");
}
}
}

public void actualFileProcess(int usersChoice) throws FileNotFoundException {
String fileName;
String badData1 = "f://goodFile.txt";
String badData2 = "f://tooFewRecs.txt";
String badData3 = "f://tooManyRecs.txt";
String badData4 = "f://nonNumericsRecCounter.txt";
String badData5 = "f://invalidData.txt";
String badData6 = "f://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 {
aFile = new File(fileName);
myfile = new Scanner(aFile);
} catch (FileNotFoundException e) {
throw new FileNotFoundException("The file " + fileName + " was not found.");
//System.out.println("WROng!");
} catch (InputMismatchException e) {

} catch (BadDataException e) {

} catch (NoSuchElementException e) {

} catch (Exception e) {
}

}

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. Invalid1 file name");

}

public void summarizeResults() {
try {
Student[] s = new Student[myfile.nextInt()];
int max = 0, min = 0;
double avg = 0;

for (int i = 0; i < s.length; i++) {
s[i] = new Student(myfile.next(), myfile.nextDouble());
if (s[i].getGpa() > s[max].getGpa()) {
max = i;
}
if (s[i].getGpa() < s[min].getGpa()) {
min = i;
}
avg += s[i].getGpa();
}
System.out.println("The student with the lowest gpa is: " + s[min].toString());
System.out.println("The student with the highest gpa is: " + s[max].toString());
System.out.println("The average of all students’ gpa is: " + avg / s.length);

} catch (Exception ex) {
throw ex;
}
}

}

output:

c3 (Build, Run) #2 x Expertques (un) X run: What type of file do you wish to read? 1. Good File 2. Too few recs in the counte

good file

5
sed 5
defg 6
www 1
qart 4
refg 8

toofewrecords

10
sed 5
defg 6
www 1
qart 4
refg 8

tomanyrecord

2
sed 5
defg 6
www 1
qart 4
refg 8

invalid data

5
sed ten
defg six
www one
qart four
refg eight

nonnumericrecordcounter

five
sed 5
defg 6
www 1
qart 4
refg 8

Add a comment
Know the answer?
Add Answer to:
Please provide the full code...the skeleton is down below: Note: Each file must contain an int...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • How would I alter this code to have the output to show the exceptions for not...

    How would I alter this code to have the output to show the exceptions for not just the negative starting balance and negative interest rate but a negative deposit as well? Here is the class code for BankAccount: /** * This class simulates a bank account. */ public class BankAccount { private double balance; // Account balance private double interestRate; // Interest rate private double interest; // Interest earned /** * The constructor initializes the balance * and interestRate fields...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

  • In the processLineOfData, write the code to handle case "H" of the switch statement such that:...

    In the processLineOfData, write the code to handle case "H" of the switch statement such that: An HourlyEmployee object is created using the firstName, lastName, rate, and hours local variables. Notice that rate and hours need to be converted from String to double. You may use parseDouble method of the Double class as follows:               Double.parseDouble(rate) Call the parsePaychecks method in this class passing the HourlyEmployee object created in the previous step and the checks variable. Call the findDepartment method...

  • Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written...

    Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written to a file. Each line of the input file will contain the student name (a single String with no spaces), the number of semester hours earned (an integer), the total quality points earned (a double). The following shows part of a typical...

  • Please help me do the java project For this project you will be reading in a...

    Please help me do the java project For this project you will be reading in a text file and evaluating it in order to create a new file that represents the Class that will represent the properties of the text file. For example, consider the following text file: students.txt ID              Name                              Age                    IsMale           GPA 1                Tom Ryan                       22                       True              3.1 2                Jack Peterson                31                       True              2.7 3                Cindy LuWho                12                       False             3.9 When you read in the header line, you...

  • JAVA PROBLEMS 1. Update the below method to throw an IndexOutOfBoundsException: public E get(int index) {...

    JAVA PROBLEMS 1. Update the below method to throw an IndexOutOfBoundsException: public E get(int index) {         if (index < 0 || index > numItems) {             System.out.println("Get error: Index "                         + index + " is out of bounds.");             return null;         }         return array[index]; } Hint: Update both the method signature and the method body! 2. Update the below method to include a try-catch block rather than throwing the exception to...

  • JAVA HELP FOR COMP: Can someone please modify the code to create LowestGPA.java that prints out...

    JAVA HELP FOR COMP: Can someone please modify the code to create LowestGPA.java that prints out the name of the student with the lowestgpa. In the attached zip file, you will find two files HighestGPA.java and students.dat. Students.dat file contains names of students and their gpa. Check if the code runs correctly in BlueJ or any other IDE by running the code. Modify the data to include few more students and their gpa. import java.util.*; // for the Scanner class...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Help check why the exception exist do some change but be sure to use the printwriter...

    Help check why the exception exist do some change but be sure to use the printwriter and scanner and make the code more readability Input.txt format like this: Joe sam, thd, 9, 4, 20 import java.io.File; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class Main1 { private static final Scanner scan = new Scanner(System.in); private static String[] player = new String[622]; private static String DATA = " "; private static int COUNTS = 0; public static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT