Question

In: Computer Science

Using Java Summary Create a Loan class, instantiate and write several Loan objects to a file,...

Using Java

Summary

Create a Loan class, instantiate and write several Loan objects to a file, read them back in, and format a report.

Project Description

You’ll read and write files containing objects of the Loan class. Here are the details of that class:

Instance Variables: customer name (String)
annual interest percentage (double)
number of years (int)
loan amount (double)
loan date (String)
monthly payment (double)
total payments (double)

Methods:

  • getters for all instance variables
  • setters for all instance variables except monthly payment and total payment
  • calculateMonthlyPayment and calculateTotalPayments

The setters for the annual interest percentage, number of years, and loan amount invoke both “calculate…” methods before they exit

The “calculate…” methods compute the named value, then store that amount in the associated instance variable. They are private (helper) methods.

Constructors:

  • a “no-arg” constructor sets the customer name to a default value, the loan date to “no date”, and all numeric variables to zero. This method invokes the “full” constructor
  • a “full” constructor takes the customer name, annual interest percentage, number of years, loan amount, and loan date. It invokes the appropriate setters, but doesn’t need to invoke the “calculate” methods (why?)

Calculations:

monthly interest rate = annual interest percentage / 1200

monthly payment = (loan amount * monthly interest rate) /
(1 – Math.pow( (1 + monthly interest rate), – (number of years * 12) ) )

total loan payments = monthly payment * number of years * 12

* Note: Round all dollar amounts to 2 decimal places

Here is what you should do in main

Use this data to create five Loan objects

                Annual Interest           Loan
  Customer Name   Percentage    Years    Amount   Loan Date
  Bob Smith             6.5%       30   318,000   Sep 1, 2015
  Alicia Herman         4.2%       15   248,000   Oct 15, 2013
  Julie Franciosa       8.5%       10    30,000   Apr 14, 2010
  Julio Quiros         15.0%        3    50,000   June 23, 2017  
  Frank Larsen          8.9%        5    23,000   Mar 8, 2016

Use this algorithm:

  1. Make the Loan class Serializable (don't forget to import this interface from java.io).
  2. Instantiate Loan objects representing the first three loans above using the “full” constructor
  3. Create an output stream and store the three objects into a binary file using the writeObject method
  4. Instantiate Loan objects representing the last two loans above using the “no-arg” constructor, then use setters to update information about those loans
  5. Append those objects to the output stream created above in step 2
  6. Close the output stream
  7. Create an input stream and read the objects from the binary file above and display in a nicely formatted columnar report
  • Write your code to handle any number of loan objects (i.e., do not assume that there are 5 Loan objects in the file -- use a loop).
  • Include in your report the monthly loan payment and total loan payment amounts
  • Display totals for the amount of the loan amounts, monthly payments, and total loan payments.
  1. Close the input stream

Note: After writing the first three Loan objects to a file (in step 2), close the output stream, then re-open the output stream before step 4 appending the last two Loan objects to the existing file

An example of the output from your program

                    Annual                    Monthly       Total 
    Customer Name   Prcnt  Yrs  Loan-Amount   Payment   Loan Payments   Loan-Date
  ----------------  -----  ---  -----------  ---------  ------------  -------------  
  Bob Smith           6.5   30   318,000.00   2,009.98    723,592.80  Sep 1, 2015
  Alicia Herman       4.2   15   248,000.00   1,859.38    334,688.40  Oct 15, 2013
  Julie Franciosa     8.5   10    30,000.00     446.35     53,562.00  Apr 14, 2010
  Julio Quiros       15.0    3    50,000.00   1,660.72     59,785.92  June 23, 2017
  Frank Larsen        8.9    5    23,000.00     476.33     28.579.80  Mar 8, 2016
                                ===========  =========  ============
                                 669,000.00   6,452.76  1,200,208.92  

Solutions

Expert Solution

//Java code

import java.text.NumberFormat;

public class Loan {
    private String customerName;
    private double annualInterest;
    private int numberOfYears;
    private double loanAmount;
    private String loanDate;
    private double monthlyPayment;
    private double totalPayments;


    //getters

    public String getCustomerName() {
        return customerName;
    }

    public double getAnnualInterest() {
        return annualInterest;
    }

    public int getNumberOfYears() {
        return numberOfYears;
    }

    public double getLoanAmount() {
        return loanAmount;
    }

    public String getLoanDate() {
        return loanDate;
    }

    public double getMonthlyPayment() {
        return monthlyPayment;
    }

    public double getTotalPayments() {
        return totalPayments;
    }

    //setters

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public void setAnnualInterest(double annualInterest) {

        this.annualInterest = annualInterest;
        calculateMonthlyPayment();
        calculateTotalPayments();
    }

    public void setNumberOfYears(int numberOfYears) {
        this.numberOfYears = numberOfYears;
        calculateMonthlyPayment();
        calculateTotalPayments();
    }

    public void setLoanAmount(double loanAmount) {
        this.loanAmount = loanAmount;
        calculateMonthlyPayment();
        calculateTotalPayments();

    }

    public void setLoanDate(String loanDate) {
        this.loanDate = loanDate;
    }
    private void calculateMonthlyPayment()
    {
        double monthlyInterestRate = annualInterest/1200.0;
        monthlyPayment = (loanAmount*monthlyInterestRate)/(1-Math.pow((1+monthlyInterestRate),-(numberOfYears*12)));

    }
    private void calculateTotalPayments()
    {

       this.totalPayments = this.numberOfYears*this.monthlyPayment*12.0;

    }
    ///no args constructor

    /***
     * a “no-arg” constructor sets the customer name to a default value,
     * the loan date to “no date”, and
     * all numeric variables to zero. This method invokes the “full” constructor
     */
    public Loan()
    {
        this("",0,0,0,"no date");

    }
    //full constructor

    /**
     * a “full” constructor takes the customer name, annual
     * interest percentage, number of years, loan amount,
     * and loan date. It invokes the appropriate setters,
     * @param customerName
     * @param annualInterest
     * @param numberOfYears
     * @param loanAmount
     * @param loanDate
     */
    public Loan(String customerName, double annualInterest, int numberOfYears, double loanAmount, String loanDate) {
       setAnnualInterest(annualInterest);
       setCustomerName(customerName);
       setLoanAmount(loanAmount);
       setLoanDate(loanDate);
       setNumberOfYears(numberOfYears);


    }






    public void display()
    {
        System.out.println(String.format("%16s %5s %6s %15s %17s %17s %17s",customerName,String.format("%.2f",annualInterest),numberOfYears, NumberFormat.getCurrencyInstance().format(loanAmount),NumberFormat.getCurrencyInstance().format(monthlyPayment),NumberFormat.getCurrencyInstance().format(totalPayments),loanDate));
    }
    @Override
    public String toString() {
        return customerName+" "+annualInterest+" "+numberOfYears+" "+loanAmount+" "+loanDate;
    }
}

//==================================

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.Scanner;

public class LoanTest {
    public static void main(String[] args) throws IOException {
       Loan loan1 = new Loan("Bob Smith",6.5,30,318000,"Sep 1, 2015");
        Loan loan2 = new Loan("Alicia Herman",4.2,15,248000,"Oct 15,2013");
        Loan loan3 = new Loan("Julie Franciosca",8.5,10,30000,"Apr 14,2010");
        PrintWriter printWriter = new PrintWriter(new FileWriter("loan.txt"));
        Loan loan4 = new Loan();
        loan4.setCustomerName("Julio Quiros");
        loan4.setNumberOfYears(3);
        loan4.setLoanAmount(50000);
        loan4.setAnnualInterest(15);
        loan4.setLoanDate("June 23, 2017");
        //============================
        Loan loan5 = new Loan();
        loan5.setCustomerName("Frank Larsen");
        loan5.setNumberOfYears(5);
        loan5.setLoanAmount(23000);
        loan5.setAnnualInterest(8.9);
        loan5.setLoanDate("Mar 8, 2016");



        //write data to file
        printWriter.println(loan1);
        printWriter.println(loan2);
        printWriter.println(loan3);
        printWriter.println(loan4);
        printWriter.println(loan5);
        printWriter.close();
        double totalLoanAmount =0,totalLoanPayment=0,totalMonthlyPayment=0;
        //header
        System.out.println(String.format("%16s %5s %6s %15s %15s %15s %15s","Customer Name","Percent","Years","Loan Amount","Payment","Loan Payments","Loan Date"));
        System.out.println(String.format("%16s %5s %4s %15s %15s %15s %15s","------------","---------","-----","-----------","-------","-------------","---------"));
        //Open stream to read
        Scanner scanFile = new Scanner(new File("loan.txt"));
        while (scanFile.hasNextLine())
        {
            String line  = scanFile.nextLine();
            Scanner words  = new Scanner(line);
            //Create loan
            Loan loan = new Loan(words.next()+" "+words.next(),words.nextDouble(),words.nextInt(),words.nextDouble(),words.nextLine());
            totalLoanAmount+=loan.getLoanAmount();
            totalLoanPayment+=loan.getTotalPayments();
            totalMonthlyPayment+=loan.getMonthlyPayment();
            loan.display();

        }
        System.out.println(String.format("%16s %5s %6s %15s %17s %17s %15s","","","","============","=============","============",""));
        System.out.println(String.format("%16s %5s %6s %15s %17s %17s %15s","","","", NumberFormat.getCurrencyInstance().format(totalLoanAmount),NumberFormat.getCurrencyInstance().format(totalMonthlyPayment),NumberFormat.getCurrencyInstance().format(totalLoanPayment),""));
        scanFile.close();

    }
}

//loan.txt

//Output

//If you need any help regarding this solution .......... please leave a comment ...... thanks


Related Solutions

JAVA Create a support class named RowSumThread.java from which you can instantiate Runnable objects, each of...
JAVA Create a support class named RowSumThread.java from which you can instantiate Runnable objects, each of which will sum one row of the two-dimensional array and then place the sum of that row into the appropriate slot of a one-dimensional, 20-element array. For your applicaiton, create MaxRowSum.java that instantiates a 20x20 two-dimentional array of integers, populates it with random integers drawn from the range 1 to 100, and then output the index of the row with the highest sum along...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount to represent a bank account according to the following requirements: A bank account has three attributes: accountnumber, balance and customer name. Add a constructor without parameters. In the initialization of the attributes, set the number and the balance to zero and the customer name to an empty string. Add a constructor with three parameters to initialize all the attributes by specific values. Add a...
Create a Java class file for a Car class. In the File menu select New File......
Create a Java class file for a Car class. In the File menu select New File... Under Categories: make sure that Java is selected. Under File Types: make sure that Java Class is selected. Click Next. For Class Name: type Car. For Package: select csci2011.lab7. Click Finish. A text editor window should pop up with the following source code (except with your actual name): csci1011.lab7; /** * * @author Your Name */ public class Car { } Implement the Car...
Using JAVA: This assignment is about aggregation and class collaboration. You will create several Classes that...
Using JAVA: This assignment is about aggregation and class collaboration. You will create several Classes that will be part of an overall class named InstrumentDisplay. The classes are FuelGage, Odometer, MilesSinceLastGas, and CruisingRange. The FuelGage should assume a 15 gallon tank of gasoline and an average consumption of 1 gallon every 28 miles. It should increment in 1 gallon steps when you "add gas to the tank". It should decrement by 1 every 28 miles. It should display its current...
Learning Outcomes Using Java, maintain a collection of objects using an array. Construct a class that...
Learning Outcomes Using Java, maintain a collection of objects using an array. Construct a class that contains an array as a private instance variable. Construct methods with arrays as parameters and return values. Use partially filled arrays to implement a class where objects can be dynamically added. Implement searching and sorting algorithms. Instructions For this assignment you will be implementing an application that manages a music collection. The application will allow the user to add albums to the collection and...
android studio -Starting with a basic activity, create a new Java class (use File->New->Java class) called...
android studio -Starting with a basic activity, create a new Java class (use File->New->Java class) called DataBaseManager as in Lecture 5 and create a database table in SQLite, called StudentInfo. The fields for the StudentInfo table include StudentID, FirstName, LastName, YearOfBirth and Gender. Include functions for adding a row to the table and for retrieving all rows, similar to that shown in lecture 5. No user interface is required for this question, t -Continuing from , follow the example in...
Create a linked list of Poem objects using the Poem.java file provided. You may create Poem...
Create a linked list of Poem objects using the Poem.java file provided. You may create Poem objects by hard coding (minimum 4), reading from a file, or getting user input. Print the list using ListIterator. Here is Poem.Java: public class Poem {    private String title;    private String poet;    /**    * No arg constructor    */    public Poem()    {        title = "not set";        poet = "not set";    }    /**...
In Java, using the code provided for Class Candle, create a child class that meets the...
In Java, using the code provided for Class Candle, create a child class that meets the following requirements. Also compile and run and show output ------------------------------------------------------------------------ 1. The child class will be named  ScentedCandle 2. The data field for the ScentedCandle class is:    scent 3. It will also have getter and setter methods 4. You will override the parent's setHeight( ) method to set the price of a ScentedCandle object at $3 per inch (Hint:   price = height * PER_INCH) CODE...
Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods...
Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods will make use of two text files. a. The first text file contains the names of cities. However, the first line of the file is a number specifying how many city names are contained within the file. For example, 5 Dallas Houston Austin Nacogdoches El Paso b. The second text file contains the distances between the cities in the file described above. This file...
in Java using netbeans create a project and in it a class with a main. We...
in Java using netbeans create a project and in it a class with a main. We will be using the Scanner class to read from the user. At the top of your main class, after the package statement, paste import java.util.Scanner; Part A ☑ In your main method, paste this code. Scanner scan = new Scanner(System.in); System.out.println("What is x?"); int x = scan.nextInt(); System.out.println("What is y?"); int y = scan.nextInt(); System.out.println("What is z?"); int z = scan.nextInt(); System.out.println("What is w?");...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT