Question

Write a program that can read XML files for customer accounts receivable, such as <ar>        <customerAccounts>...

Write a program that can read XML files for customer accounts receivable, such as

<ar>

       <customerAccounts>

              <customerAccount>

                      <name>Apple County Grocery</name>

                      <accountNumber>1001</accountNumber>

                      <balance>1565.99</balance>

              </customerAccount>

              <customerAccount>

                      <name>Uptown Grill</name>

                      <accountNumber>1002</accountNumber>

                      <balance>875.20</balance>

              </customerAccount>

       </customerAccounts>

       <transactions>

              <payment>

                      <accountNumber>1002</accountNumber>

                      <amount>875.20</amount>

              </payment>

              <purchase>

                      <accountNumber>1002</accountNumber>

                      <amount>400.00</amount>

              </purchase>

              <purchase>

                      <accountNumber>1001</accountNumber>

                      <amount>99.99</amount>

              </purchase>

              <payment>

                      <accountNumber>1001</accountNumber>

                      <amount>1465.98</amount>

              </payment>

       </transactions>

    </ar>

Your program should construct an CustomerAccountsParser object, parse the XML data & create new CustomerAccount objects in the CustomerAccountsParser for each of the products the XML data, execute all of the transactions from the file, and print the list of customers & total receivables balance. Note that there can be any number of customer accounts, and any number of purchase and payment transactions. Do not hard-code a specific number of customer accounts or transactions.

Download and use the provided ARParser.java class as the main program for your solution, and download the provided CustomerAccountsParser.java and CustomerAccount.java classes to use with your ARParser solution. Complete the parse() method in the CustomerAccountsParser to finish the program. Download and use the provided customerAccounts.xml to test your program – after the transactions, the customer accounts from the provided customerAccounts.xml file should have the results:
Customer Accounts:

1001 Apple County Grocery 200.00

1002 Uptown Grill 400.00

1003 Skyway Shop 600.00

Total balance of accounts receivable: 1200.00

(Different numbers of customer accounts and transactions will be used to test your program, so don’t assume there are only three customers in the XML data.)

To run the ARParser Java program in Eclipse, create a new project, copy the ARParser.java, CustomerAccountsParser.java, and CustomerAccount.java files into the src folder of your project, and copy the customerAccounts.xml file into the project's folder.

Files:

ARParser.java:

package Homework9;

import java.util.Scanner;

/**
This program parses an XML file containing inventory information.
It prints out the inventory inforamation after processing the
products, purchases and sales that are described in the XML file.
*/
public class ARParser
{
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
CustomerAccountsParser inventory = new CustomerAccountsParser();
System.out.print("Enter name of the customer accounts XML file: ");
String filename = in.nextLine();
inventory.parse(filename);
System.out.println("Customer Accounts:\n" + inventory.toString());
}
}

CustomerAccount.java:

package Homework9;

/**
* A simple class for Accounts Receivable:
* A CustomerAccount has a customer name, account number,
* and account balance.
* The account balance can be changed by customer purchases
* payments received.
*/
public class CustomerAccount
{
   private String name;
   private int accountNumber;
   private double accountBalance;

   /**
   * Constructs a customer account with a specified
   * name, account number, and initial balance.
   * @param newName - customer name
   * @param newAccountNumber - assigned identifier
   * @param newAccountBalance - balance on account
   */
   public CustomerAccount(String newName, int newAccountNumber,
       double newAccountBalance)
   {
       name = newName;
       accountNumber = newAccountNumber;
       accountBalance = newAccountBalance;
   }
  
   /**
   * Increases the customer's balance when the
   * customer makes a purchase.
   * @param amount - value of purchase to be added
   * to customer's account
   */
   public void purchase(double amount)
   {
       double newAccountBalance = accountBalance + amount;
       accountBalance = newAccountBalance;
   }
  
   /**
   * Reduce the customer's balance when a payment
   * is received from the customer.
   * @param amount - amount paid on account
   */
   public void payment(double amount)
   {   
       double newAccountBalance = accountBalance - amount;
       accountBalance = newAccountBalance;
   }
  
   /**
   * Gets the name for this customer's account.
   * @return the customer name
   */
   public String getName()
   {   
       return name;
   }

   /**
   * Gets the account number for this customer's account.
   * @return account number
   */
   public int getAccountNumber()
   {   
       return accountNumber;
   }

   /**
   * Gets the balance for this customer's account.
   * @return the balance
   */
   public double getAccountBalance()
   {   
       return accountBalance;
   }

   /**
   * Get a String that describes this customer account
   * @return info about this account
   */
   public String toString()
   {
       return String.format("%d %s %.2f",
               accountNumber, name, accountBalance);
   }
}

CustomerAccountsParser.java:

package Homework9;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
* This class manages a collection of customer accounts
* for an accounts receivable system.
* @author
*/
public class CustomerAccountsParser
{   
   private ArrayList<CustomerAccount> customerAccounts;
   private DocumentBuilder builder;
   private XPath path;

   /**
   * Initialize the list of customerAccounts.
   * @throws ParserConfigurationException
   */
   public CustomerAccountsParser() throws ParserConfigurationException
   {
       customerAccounts = new ArrayList<CustomerAccount>();
       DocumentBuilderFactory factory
       = DocumentBuilderFactory.newInstance();
       //factory.setValidating(true);
       factory.setIgnoringElementContentWhitespace(true);
       builder = factory.newDocumentBuilder();
       XPathFactory xpfactory = XPathFactory.newInstance();
       path = xpfactory.newXPath();
   }

   /**
   * Adds a customer account to our list.
   * @param c the customer account object to add
   */
   public void addCustomerAccount(CustomerAccount c)
   {
       customerAccounts.add(c);
   }

   /**
   * Gets the sum of the balances of all customerAccounts.
   * @return the sum of the balances
   */
   public double getTotalBalance()
   {
       double total = 0;
       for (CustomerAccount ca : customerAccounts)
       {
           total = total + ca.getAccountBalance();
       }
       return total;
   }

   /**
   * Finds a customer account with the matching account number.
   * @param number the account number to find
   * @return the customer account with the matching number
   * @throws IllegalArgumentException if there is no match
   */
   public CustomerAccount find(int number)
   {
       for (CustomerAccount ca : customerAccounts)
       {
           if (ca.getAccountNumber() == number) // Found a match
               return ca;
       }
       // No match in the entire array list
       throw new IllegalArgumentException("CustomerAccount " + number +
                       " was not found");
   }

   /**
   * Return a string that describes all the customerAccounts
   * in the accounts list.
   */
   public String toString()
   {
       double totalBalance = 0.0;
       StringBuffer sb = new StringBuffer();
       for (CustomerAccount ca : customerAccounts)
       {
           sb.append(ca.toString());
           sb.append('\n');
           totalBalance += ca.getAccountBalance();
       }
       sb.append(String.format("Total balance of accounts receivable: %.2f\n", totalBalance));
       return sb.toString();
   }
  
   /**
   * Parses an XML file containing the inventory of products.
   * @param fileName the name of the file
   */
   public void parse(String fileName)
       throws SAXException, IOException, XPathExpressionException
   {
       File f = new File(fileName);
       Document doc = builder.parse(f);

       // Count the number of customer accounts, and then get
       // each account's name, accountNumber, and balance
       // from the document, create a new CustomerAccount object,
       // and add the account object to the customer account list using addCustomerAccount().
       // Refer back to Homework 4's readCustomerAccounts() method where we created
       // a CustomerAccount object and added it to the list.

       ...;
      
       // Get and apply the purchased and sold transactions from the
       // XML document:
       // Count the account receivable purchase transactions. Then,
       // for each purchase transaction, get the account number and amount,
       // find the customer account by its accountNumber, and call the "purchase" method
       // with the amount.
       ...;

       // Count the account receivable payment transactions. Then,
       // for each payment transaction, get the account number and amount,
       // find the customer account by its accountNumber, and call the "payment" method
       // with the amount.
       ...;
   }
}

XML Document:

<?xml version="1.0"?>
<ar>
   <customerAccounts>
       <customerAccount>
           <name>Apple County Grocery</name>
           <accountNumber>1001</accountNumber>
           <balance>1565.99</balance>
       </customerAccount>
       <customerAccount>
           <name>Uptown Grill</name>
           <accountNumber>1002</accountNumber>
           <balance>875.20</balance>
       </customerAccount>
       <customerAccount>
           <name>Skyway Shop</name>
           <accountNumber>1003</accountNumber>
           <balance>443.20</balance>
       </customerAccount>
   </customerAccounts>
   <transactions>
       <payment>
           <accountNumber>1002</accountNumber>
           <amount>875.20</amount>
       </payment>
       <purchase>
           <accountNumber>1002</accountNumber>
           <amount>400.00</amount>
       </purchase>
       <purchase>
           <accountNumber>1003</accountNumber>
           <amount>600.00</amount>
       </purchase>
       <payment>
           <accountNumber>1003</accountNumber>
           <amount>443.20</amount>
       </payment>
       <purchase>
           <accountNumber>1001</accountNumber>
           <amount>99.99</amount>
       </purchase>
       <payment>
           <accountNumber>1001</accountNumber>
           <amount>1465.98</amount>
       </payment>
   </transactions>
</ar>

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

ARParser.java

import java.util.Scanner;

/**
* This program parses an XML file containing inventory information. It prints
* out the inventory inforamation after processing the products, purchases and
* sales that are described in the XML file.
*/

public class ARParser {
   public static void main(String[] args) throws Exception {
       Scanner in = new Scanner(System.in);
       CustomerAccountsParser inventory = new CustomerAccountsParser();
       System.out.print("Enter name of the customer accounts XML file: ");
       String filename = in.nextLine();
      

       inventory.parse(filename);
      
       System.out.println("Customer Accounts:\n" + inventory.toString());
   }
}

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

CustomerAccountsParser.java


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class CustomerAccountsParser extends DefaultHandler {

   private ArrayList<CustomerAccount> customerAccounts;
   private DocumentBuilder builder;

   public CustomerAccountsParser() throws ParserConfigurationException {
       customerAccounts = new ArrayList<CustomerAccount>();
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       factory.setIgnoringElementContentWhitespace(true);
       builder = factory.newDocumentBuilder();
   }

   public ArrayList<CustomerAccount> getCustomerAccounts() {
       return customerAccounts;
   }

   public double getTotalBalance() {
       double total = 0;
       for (CustomerAccount ca : customerAccounts) {
           total = total + ca.getAccountBalance();
       }
       return total;
   }

   public void addCustomerAccount(CustomerAccount c) {
       customerAccounts.add(c);
   }

   public CustomerAccount find(int number) {
       for (CustomerAccount ca : customerAccounts) {
           if (ca.getAccountNumber() == number) // Found a match
               return ca;
       }
       // No match in the entire array list
       throw new IllegalArgumentException("CustomerAccount " + number
               + " was not found");
   }

   public String toString() {
       double totalBalance = 0.0;
       StringBuffer sb = new StringBuffer();
       for (CustomerAccount ca : customerAccounts) {
           sb.append(ca.toString());
           sb.append('\n');
           totalBalance += ca.getAccountBalance();
       }
       sb.append(String.format("Total balance of accounts receivable: %.2f\n",
               totalBalance));
       return sb.toString();
   }

   public void parse(String filename) throws SAXException, IOException {
       File inputFile = new File(filename);// "C:\\test\\hackathon\\src\\apr17\\customerAccounts.xml");
       Document document = builder.parse(inputFile);

       NodeList nList = document.getElementsByTagName("customerAccounts");
       readAccount(nList, document);
       nList = document.getElementsByTagName("transactions");
       transaction(nList, document);
   }

   public void readAccount(NodeList nList, Document document) {
       for (int temp = 0; temp < nList.getLength(); temp++) {
           Node node = nList.item(temp);
           if (node.getNodeType() == Node.ELEMENT_NODE) {
               if (node.getNodeName().equalsIgnoreCase("customerAccount")) {
                   CustomerAccount ca = new CustomerAccount();
                   NodeList ns = node.getChildNodes();
                   for (int i = 0; i < ns.getLength(); i++) {
                       Node n = ns.item(i);
                       if (n.getNodeName().equalsIgnoreCase("name"))
                           ca.setName(n.getTextContent().trim());
                       else if (n.getNodeName().equalsIgnoreCase(
                               "accountNumber"))
                           ca.setAccountNumber(Integer.parseInt(n
                                   .getTextContent().trim()));
                       else if (n.getNodeName().equalsIgnoreCase("balance"))
                           ca.setAccountBalance(Double.parseDouble(n
                                   .getTextContent().trim()));
                   }
                   addCustomerAccount(ca);
               } else if (node.hasChildNodes()) {
                   readAccount(node.getChildNodes(), document);
               }

           }
       }

   }

   public void transaction(NodeList nList, Document document) {
       for (int temp = 0; temp < nList.getLength(); temp++) {
           Node node = nList.item(temp);
           if (node.getNodeType() == Node.ELEMENT_NODE) {
               if (node.getNodeName().equalsIgnoreCase("payment")) {
                   CustomerAccount ca = new CustomerAccount();
                   NodeList ns = node.getChildNodes();
                   for (int i = 0; i < ns.getLength(); i++) {
                       Node n = ns.item(i);
                       if (n.getNodeName().equalsIgnoreCase("accountNumber"))
                           ca = find(Integer.parseInt(n.getTextContent()
                                   .trim()));
                       else if (n.getNodeName().equalsIgnoreCase("amount"))
                           ca.setAccountBalance(ca.getAccountBalance()
                                   - Double.parseDouble(n.getTextContent()
                                           .trim()));

                   }
               } else if (node.getNodeName().equalsIgnoreCase("purchase")) {
                   CustomerAccount ca = new CustomerAccount();
                   NodeList ns = node.getChildNodes();
                   for (int i = 0; i < ns.getLength(); i++) {
                       Node n = ns.item(i);
                       if (n.getNodeName().equalsIgnoreCase("accountNumber"))
                           ca = find(Integer.parseInt(n.getTextContent()
                                   .trim()));
                       else if (n.getNodeName().equalsIgnoreCase("amount"))
                           ca.setAccountBalance(ca.getAccountBalance()
                                   + Double.parseDouble(n.getTextContent()
                                           .trim()));

                   }
               } else if (node.hasChildNodes()) {
                   transaction(node.getChildNodes(), document);
               }

           }
       }
   }

}

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

CustomerAccount.java


public class CustomerAccount {
   private String name;  
   private int accountNumber;
   private double accountBalance;

   /**
   * Constructs a customer account with a specified name, account number, and
   * initial balance.
   *
   * @param newName
   * - customer name
   * @param newAccountNumber
   * - assigned identifier
   * @param newAccountBalance
   * - balance on account
   */
   public CustomerAccount(String newName, int newAccountNumber,
           double newAccountBalance) {
       name = newName;
       accountNumber = newAccountNumber;
       accountBalance = newAccountBalance;
   }
  

   public CustomerAccount() {
       super();
   }


   /**
   * Increases the customer's balance when the customer makes a purchase.
   *
   * @param amount
   * - value of purchase to be added to customer's account
   */
   public void purchase(double amount) {
       double newAccountBalance = accountBalance + amount;
       accountBalance = newAccountBalance;
   }

   /**
   * Reduce the customer's balance when a payment is received from the
   * customer.
   *
   * @param amount
   * - amount paid on account
   */
   public void payment(double amount) {
       double newAccountBalance = accountBalance - amount;
       accountBalance = newAccountBalance;
   }

   /**
   * Gets the name for this customer's account.
   *
   * @return the customer name
   */
   public String getName() {
       return name;
   }

   /**
   * Gets the account number for this customer's account.
   *
   * @return account number
   */
   public int getAccountNumber() {
       return accountNumber;
   }

   /**
   * Gets the balance for this customer's account.
   *
   * @return the balance
   */
   public double getAccountBalance() {
       return accountBalance;
   }

   /**
   * Get a String that describes this customer account
   *
   * @return info about this account
   */
   public String toString() {
       return String.format("%d %s %.2f", accountNumber, name, accountBalance);
   }
  
   public void setName(String name) {
       this.name = name;
   }

   public void setAccountNumber(int accountNumber) {
       this.accountNumber = accountNumber;
   }

   public void setAccountBalance(double accountBalance) {
       this.accountBalance = accountBalance;
   }

}

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

OUTPUT:

Enter name of the customer accounts XML file: C:\\test\\customerAccounts.xml
Customer Accounts:
1001 Apple County Grocery 200.00
1002 Uptown Grill 400.00
1003 Skyway Shop 600.00
Total balance of accounts receivable: 1200.00

Add a comment
Know the answer?
Add Answer to:
Write a program that can read XML files for customer accounts receivable, such as <ar>        <customerAccounts>...
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
  • Customer Accounts This program should be designed and written by a team of students. Here are...

    Customer Accounts This program should be designed and written by a team of students. Here are some suggestions: Write a program that uses a structure to store the following information about a customer account: • Name • Address • City, state, and ZIP • Telephone number • Account balance • Date of last payment The structure should be used to store customer account records in a file. The program should have a menu that lets the user perform the following...

  • My code doesn't output correctly using a .txt file. How do I clean this up so...

    My code doesn't output correctly using a .txt file. How do I clean this up so it posts correctly? ----------------------------------------------- CODE ---------------------------------------------- #include <iostream> #include <string> #include <fstream> #include <iomanip> #include <fstream> using namespace std; struct Customer {    int accountNumber;    string customerFullName;    string customerEmail;    double accountBalance; }; void sortDesc(Customer* customerArray, int size); void print(Customer customerArray[], int size); void print(Customer customerArray[], int size) {    cout << fixed << setprecision(2);    for (int i = 0; i...

  • Hello everybody. Below I have attached a code and we are supposed to add comments explaining...

    Hello everybody. Below I have attached a code and we are supposed to add comments explaining what each line of code does. For each method add a precise description of its purpose, input and output.  Explain the purpose of each member variable. . Some help would be greaty appreciated. (I have finished the code below with typing as my screen wasnt big enough to fit the whole code image) } public void withdrawal (double amount) { balance -=amount; }...

  • NETBEANS JAVA BANK PROGRAM (TAKE SCREENSHOTS FROM NETBEANS INCLUDING OUTPUT PLEASE) Display the accounts for the...

    NETBEANS JAVA BANK PROGRAM (TAKE SCREENSHOTS FROM NETBEANS INCLUDING OUTPUT PLEASE) Display the accounts for the current displayed customer PLEASEEEEEEEEEE package bankexample; import java.util.UUID; public class Customer { private UUID id; private String email; private String password; private String firstName; private String lastName;    public Customer(String firstName, String lastName, String email, String password) { this.id = UUID.randomUUID(); this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String...

  • /* * To change this license header, choose License Headers in Project Properties. * To change...

    /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package checkingaccounttest; // Chapter 9 Part II Solution public class CheckingAccountTest { public static void main(String[] args) {    CheckingAccount c1 = new CheckingAccount(879101,3000); c1.deposit(350); c1.deposit(220); c1.withdraw(100); c1.deposit(1100); c1.deposit(700); c1.withdraw(350); c1.withdraw(220); c1.withdraw(100); c1.deposit(1100); c1.deposit(700); c1.deposit(1000); System.out.println(c1); System.out.println("After calling computeMonthlyFee()"); c1.computeMonthlyFee(); System.out.println(c1); } } class BankAccount { private int...

  • PYTHON The provided code in the ATM program is incomplete. Complete the run method of the...

    PYTHON The provided code in the ATM program is incomplete. Complete the run method of the ATM class. The program should display a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens. [comment]: <> (The ATM program allows a user an indefinite number of attempts to log in. Fix the program so that it displays a message that the police will be called...

  • Set-Up · Create a new project in your Eclipse workspace named: Lab13 · In the src...

    Set-Up · Create a new project in your Eclipse workspace named: Lab13 · In the src folder, create a package named: edu.ilstu · Import the following files from T:\it168\Labs\lab13. Note that the .txt file must be in the top level of your project, not inside your src folder. o Student.java o StudentList.java o students.txt Carefully examine the Student.java and StudentList.java files. You are going to complete the StudentList class (updating all necessary Javadoc comments), following the instruction in the code....

  • I am trying to read from a file with with text as follows and I am...

    I am trying to read from a file with with text as follows and I am not sure why my code is not working. DHH-2180 110.25 TOB-6851 -258.45 JNO-1438 375.95 CS 145 Computer Science II IPO-5410 834.15 PWV-5792 793.00 Here is a description of what the class must do: AccountFileIO 1. Create a class called AccountFileIO in the uwstout.cs145.labs.lab02 package. (This is a capital i then a capital o for input/output.) a. This class will read data from a file...

  • 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...

  • User Profiles Write a program that reads in a series of customer information -- including name,...

    User Profiles Write a program that reads in a series of customer information -- including name, gender, phone, email and password -- from a file and stores the information in an ArrayList of User objects. Once the information has been stored, the program should welcome a user and prompt him or her for an email and password The program should then use a linearSearch method to determine whether the user whose name and password entered match those of any of...

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