Question

In: Computer Science

Question: Java Programming. ** Modify Current Program. Current Program class Account{       //instance variables   ...

Question: Java Programming. ** Modify Current Program.

Current Program

class Account{
  
   //instance variables
   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;
   }

   //all getters and setters
   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 method
   public boolean deposit(double amount) {
       if(amount > 10 && amount < 200) {
           balance+=amount;
           return true;
       }
       return true;
   }
  
   //withdraw method
   public boolean withdraw(double amount) {
       if(balance-amount > 10) {
           balance -= amount;
           return true;
       }
       return false;
   }

   @Override
   public String toString() {
       return "Account [accountNumber=" + accountNumber + ", firstName=" + firstName + ", lastName=" + lastName
               + ", balance=" + balance + "]";
   }
}

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

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

public class Test{
   public static void main(String[] args)throws FileNotFoundException {
Account[] accounts = new Account[5];
       int index = 0;
      
       Scanner sc = new Scanner(new File("data.txt"));
      
       long accountNumber;
       String firstName, lastName;
       double balance;
      
       String line;
      
       //reading the file line by line
       while(sc.hasNext()) {
           line = sc.nextLine();
           String[] ar = line.split(" ");
          
           accountNumber = Long.parseLong(ar[2]);
           firstName = ar[0];
           lastName = ar[1];
           balance = Double.parseDouble(ar[3]);
          
           accounts[index++] = new Account(accountNumber, firstName, lastName, balance);
       }
      
       sc.close();
      
       displayAccount(accounts);
      
   }
  
   //for displaying account
   public static void displayAccount(Account[] acc) {
       for(Account i: acc) {
           System.out.println(i);
       }
   }
}

Modifications Needed

1) Create a File, Printwriter for an output file yourlastnameErrorLog.txt
2) Set your maximum array size for accounts to 4
3) 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, Error.txt
c. Include exception type and line number in exception message to your log file.

example:

Mismatched line: 2 line skipped
d. Continue processing the file

4) 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, Error.txt.
d. Include account number and a message account not found to the log file print,
example:
The account number you are searching for is not found: 123456
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:   12345678 balance: 760.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.

Solutions

Expert Solution

The code is present in code block below.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) throws FileNotFoundException {
        Account[] accounts = new Account[4];
        int index = 0;

        Scanner sc = new Scanner(new File("data.txt"));
        PrintWriter printWriter = new PrintWriter(new File("errorLog.txt"));

        long accountNumber;
        String firstName, lastName;
        double balance;

        String line;

        // reading the file line by line

        while (sc.hasNext()) {
            try {

                line = sc.nextLine();
                String[] ar = line.split(" ");

                accountNumber = Long.parseLong(ar[2]);
                firstName = ar[0];
                lastName = ar[1];
                balance = Double.parseDouble(ar[3]);

                accounts[index++] = new Account(accountNumber, firstName, lastName, balance);

            } catch (ArrayIndexOutOfBoundsException | InputMismatchException e) {
                // catching required exception and adding to error file.
                printWriter.println(e.getClass() + " : " + e.getLocalizedMessage());
                System.out.println(e.getClass() + " : " + e.getLocalizedMessage());
            }

        }
        sc.close();

        while (true) {
            // Accounts processing.
            long userProvidedAcntNumber;
            Scanner scanner = new Scanner(System.in);
            System.out.println("Please provide account number to process");
            userProvidedAcntNumber = scanner.nextLong();

            Account accountFound = getAccountDetails(userProvidedAcntNumber, accounts, printWriter);
            if(accountFound == null) {
                System.out.println("Invalid account number.");
                continue;
            }

            System.out.println("Account number found");

            // process the valid account now.
            processAccount(userProvidedAcntNumber, scanner, printWriter, accountFound);

            System.out.println("Do you want to process another account. Enter 1 for yes and0 for no");
            int option = scanner.nextInt();

            if(option != 1) {
                break;
            }
        }

        System.out.println("All accounts");
        displayAccount(accounts);
        printWriter.close();

    }

    private static void processAccount(long userProvidedAcntNumber, Scanner scanner, PrintWriter printWriter, Account accountFound) {

        System.out.println("Please enter your choice (1/2/3)");
        System.out.println("1. Deposit");
        System.out.println("2. Withdraw");
        System.out.println("3. Exit");

        double amount;

        int choice = scanner.nextInt();
        switch (choice) {
            case 1:
                System.out.println("Enter the amount to be deposited");
                amount = scanner.nextDouble();
                accountFound.deposit(amount);
                break;
            case 2:
                System.out.println("Enter the amount to be withdrawn");
                amount = scanner.nextDouble();
                if(accountFound.getBalance() < amount) {
                    printWriter.println("Insufficient funds for withdrawal: "+ amount + " balance: " + accountFound.getBalance());
                    System.out.println("Insufficient funds for withdrawal: "+ amount + " balance: " + accountFound.getBalance());
                }
                break;
            case 3:
            default:
                // do nothing.
                return;

        }
    }

    private static Account getAccountDetails(long userProvidedAcntNumber, Account[] accounts, PrintWriter printWriter) {

        for(int i = 0; i < accounts.length; ++i) {
            if(userProvidedAcntNumber == accounts[i].getAccountNumber()) {
                return accounts[i];
            }
        }

        printWriter.println("The account number you are searching for is not found: " + userProvidedAcntNumber);
        return null;
    }

    // for displaying account
    public static void displayAccount(Account[] acc) {
        for (Account i : acc) {
            System.out.println(i);
        }
    }
}

class Account {

    // instance variables
    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;
    }

    // all getters and setters
    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 method
    public boolean deposit(double amount) {
        if (amount > 10 && amount < 200) {
            balance += amount;
            return true;
        }
        return true;
    }

    // withdraw method
    public boolean withdraw(double amount) {
        if (balance - amount > 10) {
            balance -= amount;
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        return "Account [accountNumber=" + accountNumber + ", firstName=" + firstName + ", lastName=" + lastName
               + ", balance=" + balance + "]";
    }
}

The data.txt that I used to test is provided below.

John Cent 123 100.0
Johny Drake 124 200.0
Steve Bamer 125 250.0
Stevey John 126 350.0
Extra account 127 350.0

The ErrorLog.txt file that got generated with above input.

class java.lang.ArrayIndexOutOfBoundsException : 4
The account number you are searching for is not found: 1234
Insufficient funds for withdrawal: 10000.0 balance: 200.0

Screenshot of the code working with input and output is present below


Related Solutions

Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only...
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only run if the account status is active. You can do this adding a Boolean data member ‘active’ which describes account status (active or inactive). A private method isActive should also be added to check ‘active’ data member. This data member is set to be true in the constructor, i.e. the account is active the first time class Account is created. Add another private method...
Create a Java class named Trivia that contains three instance variables, question of type String that...
Create a Java class named Trivia that contains three instance variables, question of type String that stores the question of the trivia, answer of type String that stores the answer to the question, and points of type integer that stores the points’ value between 1 and 3 based on the difficulty of the question. Also create the following methods: getQuestion( ) – it will return the question. getAnswer( ) – it will return the answer. getPoints( ) – it will...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named coin and an object of the class Random called r. Coin will have a value of 0 or 1 (corresponding to heads or tails respectively). The constructor should take a single parameter, an int that indicates whether the coin is currently heads (0) or tails (1). There is no need to error check the input. The constructor should initialize the coin instance variable to...
You need to make an AngryBear class.(In java) The AngryBear class must have 2 instance variables....
You need to make an AngryBear class.(In java) The AngryBear class must have 2 instance variables. The first instance variable will store the days the bear has been awake. The second instance variable will store the number of teeth for the bear. The AngryBear class will have 1 constructor that takes in values for days awake and number of teeth. The AngryBear class will have one method isAngry(); An AngryBear is angry if it has been awake for more than...
Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the...
Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the program to add two more threads: add a class C and a class D, and call them from main.  Does deadlock occur? import java.util.concurrent.locks.*; class A implements Runnable {             private Lock first, second;             public A(Lock first, Lock second) {                         this.first = first;                         this.second = second;             }             public void run() {                         try {                                     first.lock();                                     System.out.println("Thread A got first lock.");                                     // do something                                     try {                                                 Thread.sleep( ((int)(3*Math.random()))*1000);...
Purpose: To write an Object-Oriented application that creates a Java class with several instance variables, a...
Purpose: To write an Object-Oriented application that creates a Java class with several instance variables, a constructor to initialize the instance variables, several methods to access and update the instance variables’ values, along with other methods to perform calculations. Also, write a test class that instantiates the first class and tests the class’s constructor and methods. Details: Create a class called Rectangle containing the following: Two instance variables, An instance variable of type double used to hold the rectangle’s width....
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name...
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name (type String), a last name (type String) and a monthly salary (double). Provide a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, do not set its value. Write a test app names EmployeeTest that demonstrates class EMLOYEE’s capabilities. Create two EMPLOYEE objects and display each object’s yearly...
Your task is to modify the program from the Java Arrays programming assignment to use text...
Your task is to modify the program from the Java Arrays programming assignment to use text files for input and output. I suggest you save acopy of the original before modifying the software. Your modified program should: contain a for loop to read the five test score into the array from a text data file. You will need to create and save a data file for the program to use. It should have one test score on each line of...
Code in Java Write a Student class which has two instance variables, ID and name. This...
Code in Java Write a Student class which has two instance variables, ID and name. This class should have a two-parameter constructor that will set the value of ID and name variables. Write setters and getters for both instance variables. The setter for ID should check if the length of ID lies between 6 to 8 and setter for name should check that the length of name should lie between 0 to 20. If the value could not be set,...
In java Implement the class Book. It has the following instance variables: name, subject, year, maximumLoanPeriod,...
In java Implement the class Book. It has the following instance variables: name, subject, year, maximumLoanPeriod, and loanPeoriod. The following methods should be included: • Constructor(s), Accessors and Mutators as needed. • public double computeFine() => calculates the fine due on this item The fine is calculated as follows: • If the loanPeriod <= maximumLoanPeriod, there is no fine on the book. • If loanPeriod > maximumLoanPeriod o If the subject of the book is "CS" the fine is 10.00...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT