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...
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 1 PROGRAMMING QUESTION In this program you will be writing a class that will contain...
JAVA 1 PROGRAMMING QUESTION In this program you will be writing a class that will contain some methods. These will be regular methods (not static methods), so the class will have to be instantiated in order to use them. The class containing the main method will be provided and you will write the required methods and run the supplied class in order to test those methods. ? Specifications There are two separate files in this program. The class containing the...
Java homework question: Explain how class (static) variables and methods differ from their instance counterparts. Give...
Java homework question: Explain how class (static) variables and methods differ from their instance counterparts. Give an example of a class that contains at least one class variable and at least one class method. Explain why using a class variable and method rather than an instance variable and method would be the correct choice in the example you select.
(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...
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...
SalaryCalculator in Java. The SalaryCalculator class should have instance variables of: an employee's name, reportID that...
SalaryCalculator in Java. The SalaryCalculator class should have instance variables of: an employee's name, reportID that is unique and increments by 10, and an hourly wage. There should also be some constructors and mutators, and accessor methods.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT