+1 678 648 4277 

Grade Calculation using Java Homework Solution


Read in scores and calculate grades

1. Create a Java Program to do the following. These tasks can all be done in the main() method. For Tasks 1-3, use a variable name of your choosing.

Create a Scanner object for keyboard input.

Create a File Object using the file name "MyGrades.txt".

Create a PrintWriter Object using the FileObject created from Step 2.

Allow PrintWrite to throw a FileNotFoundException as part of the main() method header.

Create a double variable named myGrade.

Create a do while loop with the following tasks in the loop body.

Prompt for a grade and store the result in myGrade

If myGrade is not equal to -99 - Use PrintWriter to "println" myGrade to disk.

If myGrade == -99 - The loop should exit.

Close the PrintWriter Object.

Create a Scanner Object using the File Object created in Step 2.

Create the double variables total score and average. Initialize these variables to zero.

Create the int variable counter and initialize it to zero.

Create a while loop to read each double data item found in the Scanner Object

Increment the counter variable for each loop iteration

Read the file's double variable into myGrade (As defined in Step 4)

Add myGrade to the totalScore variable.

Calculate the average as totalScore / counter

Display the counter, totalScore and Average.

Use printf and format specifiers to display the double variables in #####.## format.

Close the File Scanner object from Step 7.

Close the Scanner object from Step 1.

Example Console:

Enter Grade:100

Enter Grade:90

Enter Grade:80

Enter Grade:-99

The counter is 3, Total Grades is 270.00, Average is 90.00

2. Use the attached files for this assignment.

1. Create a new project for this assignment.

2. Copy the file 2016VotingData.txt to the base folder of this project.

3. Copy the file VoterData.java to your source folder.

4. In the method loadData(), do the following:

1. The Scanner method has an uncaught exception for the FileNotFoundException.

1. Catch this exception in the method ( do not issue a throws for the method)

2. Load the errorMessageString to read "Could not find or open File 2016VotingData.txt"

1. Do not hardcode the value "2016VotingData.txt". Instead, find the method available in the voteFile File Object to retrieve the name of this file.

3. Leave this method at this point. The main() method must complete.

2. Add ExceptionHandling ( try/catch) blocks as needed.

1. The data for DELAWARE has data that is not properly formatted for an integer.

1. Add code to your program to catch the exception given.

1. Load the errorMessageString with the phrase "BAD DATA:" and append the data line read from the file to this string.

2. Leave the method

2. Correct the data file and proceed

2. The line for VERMONT is missing expected data.

1. Add code to your program to catch the exception given.

1. Load the errorMessageString with the phrase "MISSING DATA:" and append the data line read from the file to this string.

2. Leave the method

2. Correct the data file and proceed by adding " 351" to the end of the line for VERMONT.

5. Complete TODO items and format code.

Deliverable is a corrected VoterData.java program.

Possible run results may be:

VoterData [totalRegisteredVoters=168704, errorMsg=BAD DATA:DELAWARE 729 669 487.00, hasError()=true]

VoterData [totalRegisteredVoters=168704, errorMsg=MISSING DATA:VERMONT 500 488, hasError()=true]

VoterData [totalRegisteredVoters=168704, errorMsg=null, hasError()=false]

VoterData.java

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class VoterData {

 /**

  * Load data return the total number of registered voters for 2016

  *

  */

 // Instance Data

 private int totalRegisteredVoters = 0;

 private String errorMsg;

 // Getters

 public int getTotalRegisteredVoters() {

  return totalRegisteredVoters;

 }

 public String getErrorMsg() {

  return errorMsg;

 }

 public boolean hasError() {

  boolean result;

  result = (errorMsg != null && errorMsg.length() > 0);

  return result;

 }

 /*

  * toString

  */

 @Override

 public String toString() {

  StringBuilder builder = new StringBuilder();

  builder.append("VoterData [totalRegisteredVoters=");

  builder.append(totalRegisteredVoters);

  builder.append(", errorMsg=");

  builder.append(errorMsg);

  builder.append(", hasError()=");

  builder.append(hasError());

  builder.append("]");

  return builder.toString();

 }

 /**

  *

  *

  * Load and total data

  *

  */

 public void loadData() {

  totalRegisteredVoters = 0;

  errorMsg = null;

  File voteFile = new File("2016VotingData.txt");

  Scanner input = new Scanner(voteFile);

  String line;

  String lineItems[] = new String[4];

  while (input.hasNext()) {

   line = input.nextLine();

   if (line.startsWith("#")) {

    continue; // skip this line

   }

   // remove any commas for the 3 numbers

   lineItems = line.split("\\s+"); // separate by spaces

   for (int idx = 1; idx < lineItems.length; ++idx) {

    StringBuilder myNbrString = new StringBuilder(lineItems[idx]);

    int location = myNbrString.indexOf(",");

    while (location > -1) {

     myNbrString = new StringBuilder(lineItems[idx]);

     myNbrString.deleteCharAt(location);

     location = myNbrString.indexOf(",");

    }

    lineItems[idx] = myNbrString.toString();

   }

   int stateRegistered = Integer.parseInt(lineItems[3]);

   totalRegisteredVoters += stateRegistered;

  }

  input.close();

 }

 /**

  * Test Method here

  *

  *

  */

 public static void main(String[] args) {

  VoterData voteData = new VoterData();

  voteData.loadData();

  System.out.println(voteData.toString());

 }

}

2016VotingData.txt

#State TotalPop CitizenPop RegisteredVoters

ALABAMA 3,717 3,651 2,526

ALASKA 518 502 358

ARIZONA 5,196 4,585 3,145

ARKANSAS 2,216 2,116 1,456

CALIFORNIA 29,894 24,890 16,096

COLORADO 4,242 3,895 2,893

CONNECTICUT 2,759 2,483 1,763

DELAWARE 729 669 487.00

DISTRICT OF COLUMBIA 553 512 420

FLORIDA 16,202 14,428 9,604

GEORGIA 7,626 7,048 4,892

HAWAII 1,064 974 530

IDAHO 1,224 1,150 790

ILLINOIS 9,723 8,970 6,665

INDIANA 4,988 4,795 3,298

IOWA 2,394 2,292 1,657

KANSAS 2,142 2,029 1,438

KENTUCKY 3,348 3,246 2,253

LOUISIANA 3,463 3,353 2,446

MAINE 1,058 1,038 830

MARYLAND 4,623 4,158 3,114

MASSACHUSETTS 5,374 4,967 3,660

MICHIGAN 7,624 7,332 5,434

MINNESOTA 4,190 3,985 3,055

MISSISSIPPI 2,203 2,170 1,725

MISSOURI 4,626 4,486 3,333

MONTANA 798 790 581

NEBRASKA 1,407 1,336 1,008

NEVADA 2,234 1,975 1,371

NEW HAMPSHIRE 1,044 1,012 763

NEW JERSEY 6,862 5,958 4,165

NEW MEXICO 1,547 1,396 916

NEW YORK 15,506 13,751 9,142

NORTH CAROLINA 7,631 6,960 5,194

NORTH DAKOTA 583 564 424

OHIO 8,811 8,499 6,128

OKLAHOMA 2,923 2,746 1,861

OREGON 3,185 2,929 2,147

PENNSYLVANIA 9,980 9,596 6,909

RHODE ISLAND 836 766 538

SOUTH CAROLINA 3,733 3,598 2,575

SOUTH DAKOTA 631 612 437

TENNESSEE 5,057 4,872 3,251

TEXAS 20,172 17,378 11,724

UTAH 2,096 1,969 1,398

VERMONT 500 488

VIRGINIA 6,343 5,829 4,399

WASHINGTON 5,592 5,104 3,906

WEST VIRGINIA 1,434 1,425 913

WISCONSIN 4,465 4,354 3,323

WYOMING 436 427 304

Solution:

MyGrades:

import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class Problem1 { public static void main(String[] args) throws FileNotFoundException { // 1. Create a Scanner object for keyboard input Scanner sc = new Scanner(System.in); // 2. Create a File Object using the file name "MyGrades.txt". File myGradesFile = new File("MyGrades.txt"); // 3. Create a PrintWriter Object using the FileObject created from Step 2 PrintWriter printWriter = new PrintWriter(myGradesFile); // 4. Create a double variable named myGrade. double myGrade; // 5. Create a do while loop with the following tasks in the loop body while (true) { // 1. Prompt for a grade and store the result in myGrade System.out.print("Enter Grade: "); myGrade = sc.nextDouble(); // 2. If myGrade is not equal to -99 - Use PrintWriter to "println" myGrade to disk if (myGrade != -99) { printWriter.println(myGrade); } else { //3. If myGrade == -99 - The loop should exit. break; } } // 6. Close the PrintWriter Object printWriter.close(); // 7. Create a Scanner Object using the File Object created in Step 2. Scanner fileScanner = new Scanner(myGradesFile); // 8. Create the double variables totalScore and average. Initialize these variables to zero. double totalScore = 0.0; double average = 0.0; // 9. Create the int variable counter and initialize it to zero int counter = 0; // 10. Create a while loop to read each double data item found in the Scanner Object while (fileScanner.hasNext()) { // 1. Increment the counter variable for each loop iteration counter++; // 2. Read the file's double variable into myGrade (As defined in Step 4) myGrade = fileScanner.nextDouble(); // 3. Add myGrade to the totalScore variable. totalScore += myGrade; } // 11. Calculate the average as totalScore / counter average = totalScore / counter; // 12. Display the counter, totalScore and Average. // 1. Use printf and format specifiers to display the double variables in #####.## format. System.out.printf("Counter is %d, Total Grades is %.2f, Average is %.2f\n", counter, totalScore, average); // 13. Close the File Scanner object from Step 7 fileScanner.close(); // 14. Close the Scanner object from Step 1. sc.close(); // j o h n n y t u o t - g m a i l } }

Voter Data:

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class VoterData { /** * Load data return the total number of registered voters for 2016 * */ // Instance Data private int totalRegisteredVoters = 0; private String errorMsg; // Getters public int getTotalRegisteredVoters() { return totalRegisteredVoters; } public String getErrorMsg() { return errorMsg; } public boolean hasError() { boolean result; result = errorMsg != null && errorMsg.length() > 0; return result; } /* toString */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("VoterData [totalRegisteredVoters="); builder.append(totalRegisteredVoters); builder.append(", errorMsg="); builder.append(errorMsg); builder.append(", hasError()="); builder.append(hasError()); builder.append("]"); return builder.toString(); } /** * * * Load and total data * */ public void loadData() { totalRegisteredVoters = 0; errorMsg = null; File voteFile = new File("2016VotingData.txt"); Scanner input; // 1. The Scanner method has an uncaught exception for the FileNotFoundException. try { input = new Scanner(voteFile); } catch (FileNotFoundException e) { // 1. Catch this exception in the method ( do not issue a throws for the method) // 2. Load the errorMessageString to read "Could not find or open File 2016VotingData.txt" errorMsg = String.format("Could not find or open File %s", voteFile.getName()); //System.out.println(errorMsg); // 1. Do not hardcode the value "2016VotingData.txt". Instead, find the method available in the voteFile File Object to retrieve the name of this file //3. Leave this method at this point. The main() method must complete. return; } String line; String lineItems[] = new String[4]; while (input.hasNext()) { line = input.nextLine(); if (line.startsWith("#")) { continue; // skip this line } // remove any commas for the 3 numbers lineItems = line.split("\\t+"); // separate by tab for (int idx = 1; idx < lineItems.length; ++idx) { StringBuilder myNbrString = new StringBuilder(lineItems[idx]); int location = myNbrString.indexOf(","); while (location > -1) { myNbrString = new StringBuilder(lineItems[idx]); myNbrString.deleteCharAt(location); location = myNbrString.indexOf(","); } lineItems[idx] = myNbrString.toString(); } // System.out.println("DEBUG: " + line); // for (int i = 0; i < lineItems.length; i++) { // System.out.println("\tDEBUG: " + lineItems[i]); // } if (lineItems.length != 4) { errorMsg = String.format("MISSING DATA: %s\n", line); //System.out.println(errorMsg); break; } int stateRegistered = 0; try { stateRegistered = Integer.parseInt(lineItems[3]); } catch (Exception e) { errorMsg = String.format("BAD DATA: %s\n", line); //System.out.println(errorMsg); break; } totalRegisteredVoters += stateRegistered; } input.close(); } /** * Test Method here * * */ public static void main(String[] args) { VoterData voteData = new VoterData(); voteData.loadData(); System.out.println(voteData.toString()); } }