Question

Need help Purpose Calculate mileage reimbursements using arrays and methods. The Mathematical Association of America hosts...

Need help

Purpose Calculate mileage reimbursements using arrays and methods.

The Mathematical Association of America hosts an annual summer meeting. Each state sends one official delegate to the section officers’ meeting at this summer session. The national organization reimburses the official state delegates according to the scale below. Write a Java program to calculate the reimbursement values, satisfying the specifications below. Details on array and method usage follow these specs.

1. The main method should declare all the variables at the start of the method.

2. Read data from a file and write data to a file. All data written to the output file should be echoed on the console. There should be only one input file and only one (separate) output file. The files are named, respectively,

a. YourName_S_03_Input.txt YourName is FirstnameLastname

b. YourName_S_03_Output.txt “S” is the section number

3. The first line of the input file contains an integer number of data values to process. After the first line of the input file, each line contains a type double number which is the number of miles.

4. Use an “if/else/if” construct and the scale below to calculate the mileage reimbursement if the input value is > 0.

5. Output the results to the file and to the console in a table format. (See below for a sample layout.) There should be a heading for each of the table’s columns. Print one line of output for each mileage value processed. The columns of the table should be lined up by the decimal point using the leftPad method. Each detail line of the table will contain the number of miles (double – print with one decimal place) and

the reimbursement amount (double – print with two decimal places). If the input value is <= 0, output five stars in place of the reimbursement amount.

Using a text editor or jGrasp’s File > New > Plain Text, you will need to create an input file containing the date below. Use this data in the input file to your program. DO NOT change these numbers. The first number is the number of numbers to process.

10 250.6 99.4 -2.78 999.4 799.4 1899.8 0 1300.2 1101.7 3333.3

Reimbursement scale:

Round trip mileage Rate

less than 400 miles 18 cents per mile

≥ 400, < 900 miles $ 65.00 plus 15 cents for each mile over 400

≥ 900 miles, < 1300 miles $115.00 plus 12 cents for each mile over 900

≥ 1300, < 1900 miles $140.00 plus 10 cents for each mile over 1300

≥ 1900, < 2600 miles $165.00 plus 8 cents for each mile over 1900

≥ 2600 miles $195.00 plus 6 cents for each mile over 2600

Be sure to appropriately document this program as has been discussed in class and done in previous projects.

Discussion

1. Outlining the program

2. Methods to use

3. How to test the program (sample input file: 1 250.6. i.e., use one number at a time in each scale range)

4. The leftPad method (time permitting: develop the method in class)

_____________________________________________________________________

Sample Layout for the Report

Mileage Reimbursement

---------- ---------------------

250.6 (calc’d reimbursement)

99.4 (calc’d reimbursement)

-2.8 *****

etc.

Follow the detail lines with the summary information as discussed below.

You will use two parallel one-dimensional arrays of length n, where n is the number of mileage values to process, one to hold mileage values and one to hold reimbursement values. Note that n is determined by reading the first entry in the input file which has the

number of entries that follow.

The main purpose of this project is to practice using arrays in methods. Therefore, no arrays or related counts and averages should be declared globally (static before the main program begins). You can declare constants like tab and new line as global variables if you want.

Your program must satisfy the requirements shown below. The main program should be mostly (but not necessarily only) method calls with appropriate parameters.

1. A method that explains the program to the user.

2. A method with the mileage array as a parameter that reads the mileage values and stores them in the mileage array. Use the same approach as in Project 1 to read the file. This method doesn’t calculate the reimbursement; it only reads the data. From this method, determine the number of elements in the possibly partially-filled array and return that number.

3. A method with the two arrays and the number read as parameters that calculates the array of reimbursement amounts. If the mileage value is negative or 0, the corresponding reimbursement amount should be zero.

4. One method prints the heading and another method prints the detail lines in the table. The latter method will have the two arrays and the number read as parameters.

Each detail line of the table contains the number of miles (type double, print with one decimal place) and the reimbursement amount (type double, print with two decimal places). If the input value is <= 0, output five stars instead of the reimbursement amount. Use the leftPad method to format the numbers to one or two decimal places as needed and line up the decimals in the columns.

5. After the array of reimbursements has been calculated, a method or methods calculate the average reimbursement and the average number of miles traveled. These averages will be the averages for mileage values which are > 0. In other words, you might divide by a number less than the number of elements (which, by the way, could be 0, so check for it before you calculate the average).

6. A method outputs the summary information at the end of the table. This output should include the total of the reimbursement values, the number of mileage values processed, and the number of mileage values that were > 0. In addition, output the total of the mileage values that were > 0, and the two averages calculated in the previous step, all with appropriate messages.

Outline:

import java.util.Scanner; // Access the Scanner class

import java.io.*; // Access PrintWriter and related classes

public class YourName_4_03 {

public static void main(String[ ] args) throws IOException {

// Declarations

final String INPUT_FILE = "YourName_S_04_Input.txt";

final String OUTPUT_FILE = "YourName_S_04_Output.txt";

double[] mileage; // Mileage values

double[] reimb; // Reimbursment values

int numElements = 0; // # of elements possible

int numRead = 0; // # of elements actually read

double averageMileage = 0.0; // Average of valid miles

double averageReimb = 0.0; // Average of valid reimbursements

double totalMileage = 0.0; // Total of valid miles

double totalReimb = 0.0; // Total of valid reimbursements

// Access the input and output files

File inputDataFile = new File(INPUT_FILE);

Scanner inputFile = new Scanner(inputDataFile);

FileWriter outputDataFile = new FileWriter(OUTPUT_FILE);

PrintWriter outputFile = new PrintWriter(outputDataFile);

// ******** End declarations, begin execution ********

// Get the maximum # of elements and allocate array sizes

numElements = inputFile.nextInt();

mileage = new double[numElements];

reimb = new double[numElements];

// Explain the program to the user

explainProgram(outputFile);

// Begin detailed processing

numRead = readMileage(inputFile, mileage);

calcReimbursement(mileage,reimb,numRead);

displayHeading(outputFile);

displayDetails(mileage,reimb,numRead);

averageMileage = calcAverage(mileage,numRead);

averageReimb = calcAverage(reimb,numRead);

totalMileage = calcTotal(mileage,numRead);

totalReimb = calcTotal(reimb,numRead);

} // End main

//************************************************************************

public static void explainProgram(PrintWriter output) {

} // End explainProgram

//************************************************************************

public static int readMileage(Scanner input, double[] mileage) {

int numRead = 0;

while(input.hasNext() && numRead < mileage.length) {

mileage[numRead] = input.nextDouble();

numRead++;

} // End while

return numRead;

} // End readMileage

//************************************************************************

public static void calcReimbursement(double[] mileage,

double[] reimb,

int numProcess) {

} // End calcReimbursement

//************************************************************************

public static void displayHeading(PrintWriter output) {

} // End displayHeading

//************************************************************************

public static void displayDetails(double[] mileage,

double[] reimb,

int numProcess) {

} // End displayDetails

//************************************************************************

public static double calcAverage(double[] array1, int numProcess) {

return 0.0;

} // End calcAverage

//************************************************************************

public static double calcTotal(double[] array1, int numProcess) {

return 0.0;

} // End calcTotal

} // End class

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

import java.util.Scanner; // Access the Scanner class

import java.io.*; // Access PrintWriter and related classes

public class CalculateReimbursement {

       public static void main(String[] args) throws IOException {

            

             // Declarations

             final String INPUT_FILE = "Input.txt";

             final String OUTPUT_FILE = "Output.txt";

             double[] mileage; // Mileage values

             double[] reimb; // Reimbursment values

             int numElements = 0; // # of elements possible

             int numRead = 0; // # of elements actually read

             double averageMileage = 0.0; // Average of valid miles

             double averageReimb = 0.0; // Average of valid reimbursements

             double totalMileage = 0.0; // Total of valid miles

             double totalReimb = 0.0; // Total of valid reimbursements

            

             // Access the input and output files

             File inputDataFile = new File(INPUT_FILE);

             Scanner inputFile = new Scanner(inputDataFile);

             FileWriter outputDataFile = new FileWriter(OUTPUT_FILE);

             PrintWriter outputFile = new PrintWriter(outputDataFile);

             // ******** End declarations, begin execution ********

            

             // Get the maximum # of elements and allocate array sizes

             numElements = inputFile.nextInt();

             mileage = new double[numElements];

             reimb = new double[numElements];

             // Explain the program to the user

             explainProgram(outputFile);

             // Begin detailed processing

             numRead = readMileage(inputFile, mileage);

             calcReimbursement(mileage,reimb,numRead);

             displayHeading(outputFile);

             displayDetails(mileage,reimb,numRead,outputFile);

             averageMileage = calcAverage(mileage,numRead);

             averageReimb = calcAverage(reimb,numRead);

             totalMileage = calcTotal(mileage,numRead);

             totalReimb = calcTotal(reimb,numRead);

            

             outputFile.write(String.format("\nTotal Mileage = %.2f\n",totalMileage));

             outputFile.write(String.format("Average Mileage = %.2f\n",averageMileage));

             outputFile.write(String.format("Total Reimbursement = $%.2f\n",totalReimb));

             outputFile.write(String.format("Average Reimbursement = $%.2f\n",averageReimb));

            

             System.out.printf("\nTotal Mileage = %.2f\n",totalMileage);

             System.out.printf("Average Mileage = %.2f\n",averageMileage);

             System.out.printf("Total Reimbursement = $%.2f\n",totalReimb);

             System.out.printf("Average Reimbursement = $%.2f",averageReimb);

            

             inputFile.close();

             outputFile.close();

       }// End main

      

       //************************************************************************

       public static void explainProgram(PrintWriter output) {

            

             output.write("This program calculates the Mileage Reimbursement according to the given scale.\n\n");

             System.out.println("This program calculates the Mileage Reimbursement according to the given scale.\n");

       } // End explainProgram

      

       //************************************************************************

       public static int readMileage(Scanner input, double[] mileage) {

      

             int numRead = 0;

      

             while(input.hasNext() && numRead < mileage.length) {

                    mileage[numRead] = input.nextDouble();

                    numRead++;

      

             } // End while

      

             return numRead;

       } // End readMileage

      

       //************************************************************************

       public static void calcReimbursement(double[] mileage, double[] reimb, int numProcess) {

             for(int i=0;i<numProcess;i++)

             {

                    if(mileage[i] <= 0)

                           reimb[i] = 0;

                    else if(mileage[i] < 400)

                           reimb[i] = 0.18*mileage[i];

                    else if(mileage[i] < 900)

                           reimb[i] = 65 + 0.15*(mileage[i] - 400);

                    else if(mileage[i] < 1300 )

                           reimb[i] = 115 + 0.12*(mileage[i] - 900);

                    else if(mileage[i] < 1900)

                           reimb[i] = 140 + 0.10*(mileage[i] - 1300);

                    else if(mileage[i] < 2600)

                           reimb[i] = 165 + 0.08*(mileage[i] - 1900);

                    else

                           reimb[i] = 195 + 0.06*(mileage[i] - 2600);

             }

            

       } // End calcReimbursement

       //************************************************************************

       public static void displayHeading(PrintWriter output) {

             output.write(String.format("%20s%20s\n", "Mileage","Reimbursement"));

             output.write(String.format("%11s-----------------------------\n"," "));

             System.out.printf("%20s%20s\n", "Mileage","Reimbursement($)");

             System.out.printf("%11s-----------------------------\n"," ");

       } // End displayHeading

       //************************************************************************

       public static void displayDetails(double[] mileage, double[] reimb, int numProcess, PrintWriter output) {

             for(int i=0;i<numProcess;i++)

             {

                    if(mileage[i] <= 0)

                    {

                           output.write(String.format("%20.2f%20s\n",mileage[i],"*****"));

                           System.out.printf("%20.2f%20s\n",mileage[i],"*****");

                    }else

                    {

                           output.write(String.format("%20.2f%20.2f\n",mileage[i],reimb[i]));

                           System.out.printf("%20.2f%20.2f\n",mileage[i],reimb[i]);

                    }

                          

             }

       } // End displayDetails

      

       //************************************************************************

       public static double calcAverage(double[] array1, int numProcess) {

             double total = 0;

             int count = 0;

             for(int i=0;i<numProcess;i++)

             {

                    if(array1[i] > 0)

                    {

                           total+= array1[i];

                           count++;

                    }

             }

            

             return(total/count);

       } // End calcAverage

       //************************************************************************

       public static double calcTotal(double[] array1, int numProcess) {

             double total = 0;

             for(int i=0;i<numProcess;i++)

             {

                    if(array1[i] > 0)

                           total+= array1[i];

             }

             return total;

       } // End calcTotal

}// End class

//end of program

Output:

Input file

Output:

Add a comment
Know the answer?
Add Answer to:
Need help Purpose Calculate mileage reimbursements using arrays and methods. The Mathematical Association of America hosts...
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
  • pls help java ASAP!!!!!!! Topic String Tokenizer Static Methods Static Variables Primitive Arrays Description Enhance the...

    pls help java ASAP!!!!!!! Topic String Tokenizer Static Methods Static Variables Primitive Arrays Description Enhance the last assignment by providing the following additional features: (The additional features are listed in bold below) Class Statistics In the class Statistics, create the following static methods (in addition to the instance methods already provided). • A public static method for computing sorted data. • A public static method for computing min value. • A public static method for computing max value. • A...

  • Using the following create the nessecary static methods to pass random arrays with the TempartureWithArrays and...

    Using the following create the nessecary static methods to pass random arrays with the TempartureWithArrays and Temperature classes -------------------------------------------------------------------------------------- public class TemperatureWithArrays {    public static final int ARRAY_SIZE = 5;    public static void main(String[] args)    {        int x;        Temperature temp1 = new Temperature(120.0, 'C');        Temperature temp2 = new Temperature(100, 'C');        Temperature temp3 = new Temperature(50.0, 'C');        Temperature temp4 = new Temperature(232.0, 'K');        Temperature tempAve =...

  • Fibtester: package fibtester; // Imported to open files import java.io.File; // Imported to use the exception...

    Fibtester: package fibtester; // Imported to open files import java.io.File; // Imported to use the exception when files are not found import java.io.FileNotFoundException; // Imported to write to a file import java.io.PrintWriter; // Imported to use the functionality of Array List import java.util.ArrayList; // Imported to use the exceptions for integer values import java.util.NoSuchElementException; // Imported to use when the array is out of bounds import java.lang.NullPointerException; // Imported to take input from the user import java.util.Scanner; public class FibTester...

  • JAVA: amortization table: Hi, I have built this code and in one of my methods: printDetailsToConsole...

    JAVA: amortization table: Hi, I have built this code and in one of my methods: printDetailsToConsole I would like it to print the first 3 payments and the last 3 payments if n is larger than 6 payments. Please help! Thank you!! //start of program import java.util.Scanner; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.lang.Math; //345678901234567890123456789012345678901234567890123456789012345678901234567890 /** * Write a description of class MortgageCalculator here. * * @author () * @version () */ public class LoanAmortization {    /* *...

  • 14.8 Prog 8 Overload methods (find avg) Write a program to find the average of a...

    14.8 Prog 8 Overload methods (find avg) Write a program to find the average of a set numbers (assume that the numbers in the set is less than 20) using overload methods. The program first prompts the user to enter a character; if the character is 'I' or 'i', then invokes the appropriate methods to process integer data set; if the character is 'R' or 'r', then invokes the appropriate methods to process real number data set; if the inputted...

  • //please help I can’t figure out how to print and can’t get the random numbers to...

    //please help I can’t figure out how to print and can’t get the random numbers to print. Please help, I have the prompt attached. Thanks import java.util.*; public class Test { /** Main method */ public static void main(String[] args) { double[][] matrix = getMatrix(); // Display the sum of each column for (int col = 0; col < matrix[0].length; col++) { System.out.println( "Sum " + col + " is " + sumColumn(matrix, col)); } } /** getMatrix initializes an...

  • Thank you! /*Lab 8 : Practicing functions and arrays Purpose: */ #include<iostream> #include<fstream> using namespace std;...

    Thank you! /*Lab 8 : Practicing functions and arrays Purpose: */ #include<iostream> #include<fstream> using namespace std; int read_function(int array[], int, int); int main() { int array[300], numba; read_function(array[300]); cout << "Enter a whole number between 2-20: " << endl; cin >> numba; read_function(numba); return 0; } int read_funtion (int arr[300], int num, int Values) { int sum=0; ifstream array_file; array_file.open("Lab8.dat"); for(int i=0; i < 300; i++) {   array_file >> arr[i];   cout << arr[i];   sum += i; } cout << sum;...

  • I currently have this but it doesn't work for the three item arrays public class Quicksort...

    I currently have this but it doesn't work for the three item arrays public class Quicksort extends Partitioner { public static void quicksort(int[] values) { if (values == null || values.length < 2) { return; } quicksort(values, 0, values.length - 1); } private static void quicksort(int[] values, int start, int end) { System.out.println(values); System.out.println(start); System.out.println(end); if (values == null || Math.abs(start - end) == 1) { return; } if (end > start) { int pivotValueIndex = partition(values, start, end); quicksort(values,...

  • Parallel Arrays Summary In this lab, you use what you have learned about parallel arrays to...

    Parallel Arrays Summary In this lab, you use what you have learned about parallel arrays to complete a partially completed Java program. The program should either print the name and price for a coffee add-in from the Jumpin’ Jive coffee shop or it should print the message: "Sorry, we do not carry that.". Read the problem description carefully before you begin. The data file provided for this lab includes the necessary variable declarations and input statements. You need to write...

  • Hi I need some help on this lab. The world depends on its successfull compilation. /*...

    Hi I need some help on this lab. The world depends on its successfull compilation. /* Lab5.java Arrays, File input and methods Read the comments and insert your code where indicated. Do not add/modify any output statements */ import java.io.*; import java.util.*; public class Lab5 { public static void main (String[] args) throws Exception { final int ARRAY_MAX = 30; // "args" is the list of tokens you put after "java Project3" on command line if (args.length == 0 )...

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