Question

In: Computer Science

Required methods:: public static void processAccount (Account[] acc, printWriter out{}. public static boolean deposit(Account a){}.

Java programming.

Required methods::
public static void processAccount (Account[] acc, printWriter out{}.
public static boolean deposit(Account a){}.
public static boolean withdrawal(Account a){}.
public static int findAccount(long accountNumber, Account[] acc){}.


1/ Remove the applyRandomBonus method from the test class
2/ Create a File, Printwriter for an output file yourlastnameErrorLog.txt
4/ Catch InputMismatch and ArrayIndexOutOfBounds exceptions when reading data from the file:
a. Skip any lines that cause an exception
b. Write information about the exception to the log file, yourlastnameError.txt
c. Include exception type and line number in exception message to your log file.
Example:
Data   Input   Mismatch   line:3   line   skipped
d. Continue processing the file
5/ Add Account Processing for the user to deposit or withdraw from an account:
a. Ask the user if they would like to process account(s)
b. Ask the user for account number
c. Search for account (using a separate method for your linear search), print and
error if account not found to the screen and to the log file,
yourlastnameError.txt.
d. Include account number and a message account not found to the log file print,
example:
Account   number   searched for not found: 555555
e. Once account is found, send it to a separate method that will handle
withdrawals and deposits. Ask the user if they would like to Deposit, Withdraw
or Exit. Print an error message to the screen and to the log file if the deposit or
withdrawal did not go through (see requirements from Phase 1). Include
account number of unsuccessful action, and the action (withdrawal, deposit) to
your error message, example:
Insufficient   funds   for   withdrawal:   5023742 balance:   540.0
f. Once the user is done with deposits/withdrawals for an account, loop around
and ask again if they’d like to process another account.
6/ All requirements from Final Phase 1 are required in this project, except for the
appyRandomBonus method and method call.

public class Account {
private long accountNumber;
private String firstName;
private String lastName;
private double balance;
// constructor
public Account(long accountNumber, String firstName, String lastName, double balance) {
this.accountNumber = accountNumber;
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;
}

// setters and getters
public long getAccountNumber() {
return accountNumber;
}

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

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public double getBalance() {
return balance;
}

public void setBalance(double balance) {
this.balance = balance;
}


// deposit
public boolean deposit(double amount) {
boolean isDeposit = false;
if(amount>10 && amount <200) {
this.balance +=amount;
isDeposit = true;
}

return isDeposit;
}

public boolean withdraw(double amount) {
boolean isWithdraw = false;

if(amount>=10 && this.balance>=10) {
this.balance-=amount;
isWithdraw = true;
}
return isWithdraw;
}

// toString method is used to return current object data in the form of string
@Override
public String toString() {
return "Account{" +
"accountNumber=" + accountNumber +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", balance=" + balance +
'}';
}
}
*************
Test class:::

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class AccountTest {
static int index=0;
public static void main(String[] args) throws FileNotFoundException {

Account [] accounts = new Account[10];
Scanner scanner = new Scanner(new File("E:\\Data.txt"));
/* This method will get each line from the text file and split with the space and then saved each attribute
* into corresponding element.*/
while (scanner.hasNextLine()) {
String eachLine = scanner.nextLine();
String splitLine[] = eachLine.split(" ");

for (int i=0; i<splitLine.length;i++) {
String firstName = splitLine[i];
String lastName = splitLine[++i];
long accountNumber = Long.parseLong(splitLine[++i]);
double balance = Double.parseDouble(splitLine[++i]);
accounts[index] = new Account(accountNumber,firstName,lastName,balance);
index++;
}
}

// static methods
displayAccounts(accounts);
applyRandomBonus(accounts);
displayAccounts(accounts);

System.out.println("Check deposit and withdraw:");
System.out.println(accounts[0]);
System.out.println(accounts[0].deposit(300));
System.out.println(accounts[0]);
System.out.println(accounts[0].withdraw(215));
System.out.println(accounts[0]);
}
private static void applyRandomBonus(Account[] accounts) {
for(Account account: accounts) {
if(account!=null) {
// Here random number can be generated between 100 and 300
int randomNumber = (int) (100+Math.random()*(300-100));
System.out.println("Bonus: " +randomNumber);
// adding each bonus into account balance
account.setBalance(account.getBalance()+randomNumber);
}
}
}
private static void displayAccounts(Account[] accounts) {

// By using for each loop displays the details of account
for(Account account: accounts) {
if(account!=null) {
System.out.println(account); d
}
}
}
}
** data.txt include:
1/ Johnson Nell 98845255 28.00
2/ Kendrick Farwell 67854321 100.00
3/ Peter Jackson 55325678 400.00
4/ Layla Kerns 56789332 350.00
5/ London Parker 23412378 250.00

**ErrorLog.txt::

mistmatch

mistmatch

Data Input Mismatch line :3 line skipped

Data Input Mismatch line :9 line skipped

output::

mistmatch

mistmatch

Would you like to process accounts?(y/n)
y
Enter account number
98845255
Deposit or Withdraw or Exit? (D/W/E) for account: 98845255, 567.0:
500
Deposit or Withdraw or Exit? for account: 98845255, 567.0:
W
Enter amount
200
Deposit or Withdraw or Exit? (D/W/E) for account: 98845255, 567.0:
E
Thank you.
Would you like to process accounts?(y/n)
y
Enter account number
55325678
Deposit or Withdraw or Exit? (D/W/E) for account: 55325678, 222.0:
500
Deposit or Withdraw or Exit? for account: 55325678, 222.0:
W
Enter amount
200
Deposit or Withdraw or Exit? (D/W/E) for account: 55325678, 222.0:
N
Account{accountNumber=98845255, firsName='Johnson', lastName='Nell', balance= 567.0}
Account{accountNumber=67854321, firsName='Kendrick', lastName='Farwell', balance= 450.0}
Account{accountNumber=55325678, firsName='Peter', lastName='Jackson', balance= 222.0}
Account{accountNumber=56789332, firsName='Layla', lastName='Kerns', balance= 762.0}
Account{accountNumber=23412378, firsName='London ', lastName='Parker', balance= 791.0}

Solutions

Expert Solution

Here is the Java code for your problem. Working for all test cases. Before running the code, make you have the same txt files in same directory. I have done some modifiations in Data.txt so that I can record it in error log.

Data.txt

Johnson Nell 98845255 28.00
230 Kendrick Farwell 67854321 100.00
Peter Jackson 55325678
Layla Kerns 56789332 350.00
London Parker 23412378 250.00

AccountTest.java

////
import java.io.*;
import java.util.Scanner;
import java.util.Locale;



public class AccountTest {
    static int index=0, line=0;



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

        Account [] accounts = new Account[10];
        Scanner scanner = new Scanner(new File("Data.txt"));
        //creating PrintWriter object to write error log
        PrintWriter out = new PrintWriter(new File("yourlastnameError.txt"));
        /* This method will get each line from the text file and split with the space and then saved each attribute
        * into corresponding element.*/
        while (scanner.hasNextLine()) {
            String eachLine = scanner.nextLine();
            String splitLine[] = eachLine.split(" ");
            int i=0;
            try{
                String firstName = splitLine[i];
                String lastName = splitLine[++i];
                long accountNumber = Long.parseLong(splitLine[++i]);
                double balance = Double.parseDouble(splitLine[++i]);
                accounts[index] = new Account(accountNumber,firstName,lastName,balance);
                index++;
            }
            //catches the error if the data is not in right format
            catch(Exception e){
                //add error log to PrintWriter
                out.format(Locale.UK, "Data   Input   Mismatch   line:%d   line   skipped\n", line);
            }
            //increment line value
            line++;
        }

        // display all valid accounts
        displayAccounts(accounts);
        //calling processAccount function() 
        processAccount(accounts, out);
        // display all accounts after processing
        displayAccounts(accounts);
        //flush data into the PrintWriter object 'out' and close it
        out.flush();
        out.close();
    }
    //method to display all accounts in accounts array
    private static void displayAccounts(Account[] accounts) {

    // By using for each loop displays the details of account
        for(Account account: accounts) {
            if(account!=null) {
                System.out.println(account);
            }
        }
    }
    //a function to process the accounts in given accounts array
    public static void processAccount (Account[] acc, PrintWriter out){
        //scanner for user input
        Scanner sc = new Scanner(System.in);
        //declare required variables
        char response, action;
        double amount;
        long account;
        //loop runs until user exit from processing
        do{
            //taking user decision to continue or not
            System.out.print("Would you like to process accounts?(y/n)\n");
            response = sc.next().charAt(0);
            //ask the user for decision until it is valid
            while(response!='y' && response!='n' && response!='Y' && response!='N'){
                System.out.print("Would you like to process accounts?(y/n)\n");
                response = sc.next().charAt(0);
            }
            //if response is n/N then exit from the loop
            if(response == 'n' || response == 'N')
                return;
            //taking user input for account number
            System.out.print("Enter account number\n");
            account = sc.nextLong();
            int ind = findAccount(account, acc);
            //ask user for acount number until it is a valid account number in the given array
            while(ind==-1){
                //if the account number is not valid, add to log and print message
                out.format(Locale.UK, "Account   number   searched for not found: %d\n", account);
                System.out.print("Account not found!\nEnter account number\n");
                //again take input
                account = sc.nextLong();
                ind = findAccount(account, acc);
            }
            //loop runs until user want to exit from proessing the given account
            do{
                //taking user option for deposit/withdrawal/exit
                System.out.printf("Deposit or Withdraw or Exit? (D/W/E) for account: %d, %.1f: \n", account, acc[ind].getBalance());
                action = sc.next().charAt(0);
                //if user option is n/N then exit from loop
                if(action == 'n' || action  == 'N')
                    return;
                //if user option is d/D
                else if(action == 'D' || action  == 'd'){
                    //take user input for amount
                    System.out.print("Enter amount\n");
                    amount = sc.nextDouble();
                    //call deposit function and add to error log if failed 
                    if(!deposit(acc[ind], amount)){
                        out.format(Locale.UK, "Failed to deposit:   %d balance:   %.1f\n", account, acc[ind].getBalance());
                        System.out.println("Failed to deposit");
                    }
                    //if not failed, print Done
                    else System.out.println("Done");
                }
                //if user option is w/W
                else if(action  == 'W' || action  == 'w'){
                    //take user input for amount
                    System.out.print("Enter amount\n");
                    amount = sc.nextDouble();
                    //call withdrawal function and add to error log if failed 
                    if(!withdrawal(acc[ind], amount)){
                        out.format(Locale.UK, "Insufficient   funds   for   withdrawal:   %d balance:   %.1f\n", account, acc[ind].getBalance());
                        System.out.printf("Failed to withdraw:   %d balance:   %.1f\n", account, acc[ind].getBalance());
                    }
                    //if not failed, print Done
                    else System.out.println("Done");
                }

            }while(action != 'E' && action != 'e'); //exit when user option is E/e


        }while(true);
    }
    //function to perform deposit and return boolean value
    public static boolean deposit(Account a, double amount){
        return a.deposit(amount);
    }
    //function to perform withdrawl and return boolean value
    public static boolean withdrawal(Account a, double amount){
        //if the amount is less than balance perform withdrawal
        if(amount <= a.getBalance()){
            //perform withdrawal and return true if done
            if(a.withdraw(amount)){
                return true;
            }
        }
        //else retrurn false
        return false;
    }
    //function to return index position of account having given accountNumver in the acc Array
    public static int findAccount(long accountNumber, Account[] acc){

        for(int i=0; i<acc.length; i++) {
            try{
                //if found return index
                if(acc[i].getAccountNumber() == accountNumber) {
                    return i;
                }
            }
            //catches null pointer exception
            catch(Exception e){
                break;
            }
        }
        //if not found return -1
        return -1;
    }
}



class Account {
    private long accountNumber;
    private String firstName;
    private String lastName;
    private double balance;
// constructor
    public Account(long accountNumber, String firstName, String lastName, double balance) {
        this.accountNumber = accountNumber;
        this.firstName = firstName;
        this.lastName = lastName;
        this.balance = balance;
    }

    // setters and getters
    public long getAccountNumber() {
        return accountNumber;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }


    // deposit
    public boolean deposit(double amount) {
        boolean isDeposit = false;
        if(amount>10 && amount <200) {
            this.balance +=amount;
            isDeposit = true;
        }

        return isDeposit;
    }

    public boolean withdraw(double amount) {
        boolean isWithdraw = false;

        if(amount>=10 && this.balance>=10) {
            this.balance-=amount;
            isWithdraw = true;
        }
        return isWithdraw;
    }

    // toString method is used to return current object data in the form of string
    @Override
    public String toString() {
        return "Account{" + "accountNumber=" + accountNumber + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' +", balance=" + balance +'}';
    }
}

/////

OUTPUT:

yourlastnameError.txt after program

Data Input Mismatch line:1 line skipped
Data Input Mismatch line:2 line skipped
Account number searched for not found: 1234
Failed to deposit: 56789332 balance: 350.0
Insufficient funds for withdrawal: 56789332 balance: 500.0

CODE IMAGES:

 


Related Solutions

Consider the following code: public class Example { public static void doOp(Op op) { boolean result...
Consider the following code: public class Example { public static void doOp(Op op) { boolean result = op.operation(true, false); System.out.println(result); } public static void main(String[] args) { doOp(new AndOperation()); doOp(new OrOperation()); } } main's output: false true Define any interfaces and/or classes necessary to make this output happen. Multiple answers are possible. You may not modify any of the code in Example.
Consider the following two methods: public static boolean isTrue(int n){ if (n <= 1)          return false;...
Consider the following two methods: public static boolean isTrue(int n){ if (n <= 1)          return false;        for (int i = 2; i < n; i++){          if (n % i == 0)             return false; }        return true; } public static int Method(int[] numbers, int startIndex) { if(startIndex >= numbers.length) return 0; if (isTrue(numbers[startIndex]))      return 1 + Method(numbers, startIndex + 1); else      return Method(numbers, startIndex + 1); } What is the final return value of Method() if it is called with the...
public class Problem1 {    public static void partition(int[] A)    {        /*Rearrange the...
public class Problem1 {    public static void partition(int[] A)    {        /*Rearrange the array to have the following property:        Suppose the first element in the original array has the value x.        In the new array, suppose that x is in position i, that is data[i] = x.        Then, data[j] <= x for all j < I and data[j] > x for all j > i.        Thus, informally, all the...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare variables int hrsWrked; double ratePay, taxRate, grossPay, netPay=0; string lastName; // enter the employee's last name Console.Write("Enter the last name of the employee => "); lastName = Console.ReadLine(); // enter (and validate) the number of hours worked (positive number) do { Console.Write("Enter the number of hours worked (> 0) => "); hrsWrked = Convert.ToInt32(Console.ReadLine()); } while (hrsWrked < 0); // enter (and validate) the...
public class OOPExercises {     public static void main(String[] args) {         A objA = new...
public class OOPExercises {     public static void main(String[] args) {         A objA = new A();         B objB = new B();         System.out.println("in main(): ");         System.out.println("objA.a = "+objA.getA());         System.out.println("objB.b = "+objB.getB());         objA.setA (222);         objB.setB (333.33);       System.out.println("objA.a = "+objA.getA());         System.out.println("objB.b = "+objB.getB());     } } Output: public class A {     int a = 100;     public A() {         System.out.println("in the constructor of class A: ");         System.out.println("a = "+a);         a =...
public class GreeterTest {    public static void main(String[] args)    { // create an object...
public class GreeterTest {    public static void main(String[] args)    { // create an object for Greeter class Greeter greeter = new Greeter("Jack"); // create two variables Greeter var1 = greeter; Greeter var2 = greeter; // call the sayHello method on the first Greeter variable String res1 = var1.sayHello(); System.out.println("The first reference " + res1); // Call the setName method on the secod Grreter variable var2.setName("Mike"); String res2 = var2.sayHello(); System.out.println("The second reference " + res2);    } }...
public class ArraySkills { public static void main(String[] args) { // *********************** // For each item...
public class ArraySkills { public static void main(String[] args) { // *********************** // For each item below you must code the solution. You may not use any of the // methods found in the Arrays class or the Collections classes // You must use Java's built-in Arrays. You are welcome to use the Math and/or Random class if necessary. // You MUST put your code directly beneath the comment for each item indicated. String[] myData; // 1. Instantiate the given...
import java.util.Random; class Conversions { public static void main(String[] args) { public static double quartsToGallons(double quarts)...
import java.util.Random; class Conversions { public static void main(String[] args) { public static double quartsToGallons(double quarts) { return quarts * 0.25; } public static double milesToFeet(double miles) { return miles * 5280; } public static double milesToInches(double miles) { return miles * 63360; } public static double milesToYards(double miles) { return miles * 1760; } public static double milesToMeters(double miles) { return miles * 1609.34; } public static double milesToKilometer(double miles) { return milesToMeters(miles) / 1000.0; } public static double...
public class Main { public static void main(String [] args) { int [] array1 = {5,...
public class Main { public static void main(String [] args) { int [] array1 = {5, 8, 34, 7, 2, 46, 53, 12, 24, 65}; int numElements = 10; System.out.println("Part 1"); // Part 1 // Enter the statement to print the numbers in index 5 and index 8 // put a space in between the two numbers and a new line at the end // Enter the statement to print the numbers 8 and 53 from the array above //...
---------------------------------------------------------------------------- public class Main { public static void main(String[] args) { int[] A = {11, 12,...
---------------------------------------------------------------------------- public class Main { public static void main(String[] args) { int[] A = {11, 12, -10, 13, 9, 12, 14, 15, -20, 0}; System.out.println("The maximum is "+Max(A)); System.out.println("The summation is "+Sum(A)); } static int Max(int[] A) { int max = A[0]; for (int i = 1; i < A.length; i++) { if (A[i] > max) { max = A[i]; } } return max; } static int Sum(int[] B){ int sum = 0; for(int i = 0; i --------------------------------------------------------------------------------------------------------------------------- Convert...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT