Part of my assignment was to have the user input an Eployee Id between 0-9 and contains a letter between A-M(ex. 999-M), and then if it doesn't meet one of the criteria it is supposed to throw an error code using an exception class. I figured out how to check the Id, but only works with the number part. I have no clue how to check if the input also meets the letter criteria. I know it has something to do with employee Id being an int and not a string, but when I attempted to fix it. I almost messed my whole code up. Any help would be appreciated.
My main code:
package payrollexceptions;
import java.util.Scanner;
public class PayRollExceptions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Payroll employee = new Payroll();
String name;
int employeeId;
double payRate;
System.out.print("Enter the employee's name: ");
employee.setName(keyboard.nextLine());
System.out.print("Enter employee number, (ex. 999-M): ");
employee.setEmployeeId(keyboard.nextInt());
System.out.print("Enter the employee's hourly rate: ");
employee.setPayRate(keyboard.nextDouble());
System.out.print("Enter the number of hours the employee has worked: ");
employee.setHours(keyboard.nextInt());
System.out.println("\n" + employee.getName());
System.out.println("-----------");
System.out.println("ID: " + employee.getEmployeeId());
System.out.println("Pay rate: $" + employee.getPayRate());
System.out.println("Hours worked: $" + employee.getHours());
System.out.println("Gross pay: $" + employee.getGrossPay());
}
}
The code that involves setting the employeeId:
package payrollexceptions;
public class Payroll
{
private int employeeId, hours;
private double payRate;
private String name;
public Payroll() {}
public Payroll(String name, int employeeId, double payRate)
{
try
{
if(name == "")
{
throw new EmptyNameException();
}
setName(name);
if(employeeId <= 0)
{
throw new InvalidEmployeeIdException();
}
setEmployeeId(employeeId);
if(payRate < 0 || payRate > 25)
{
throw new InvalidPayRateException();
}
setPayRate(payRate);
}
catch(EmptyNameException e)
{
System.out.println("Error: the employee's name cannot be blank");
System.exit(1);
}
catch(InvalidEmployeeIdException e)
{
System.out.println("Error: the employee's id must be above 0");
System.exit(1);
}
catch(InvalidPayRateException e)
{
System.out.println("Error: the payrate must not be negative nor exceed 25");
System.exit(1);
}
setEmployeeId(employeeId);
setPayRate(payRate);
}
public double getGrossPay()
{
return payRate * hours;
}
public int getEmployeeId()
{
return employeeId;
}
public int getHours()
{
return hours;
}
public double getPayRate()
{
return payRate;
}
public String getName()
{
return name;
}
public void setEmployeeId(int employeeId)
{
try
{
if(employeeId <= 0)
{
throw new InvalidEmployeeIdException();
}
this.employeeId = employeeId;
}
catch(InvalidEmployeeIdException e)
{
System.out.println("Error: Numericals in ID must be between 0-9 and letters must be between A-M");
System.exit(1);
}
}
public void setHours(int hours)
{
try
{
if(hours < 0 || hours > 84)
{
throw new InvalidHoursException();
}
this.hours = hours;
}
catch(InvalidHoursException e)
{
System.out.println("Error: Hours Cannot be negative or greater than 84");
System.exit(1);
}
}
public void setPayRate(double payRate)
{
try
{
if(payRate < 0 || payRate > 25)
{
throw new InvalidPayRateException();
}
this.payRate = payRate;
}
catch(InvalidPayRateException e)
{
System.err.println("Error: Hourly Rate Cannot be negative or greater than 25");
System.exit(1);
}
}
public void setName(String name)
{
try
{
if(name.isEmpty())
{
throw new EmptyNameException();
}
this.name = name;
}
catch(EmptyNameException e)
{
System.out.println("Error: the employee's name cannot be blank");
System.exit(1);
}
}
}
Related
I've developed some code and all my methods use a custom object I created called account. I'm now splitting account into two different types of account, deposit account and savings account. My issue is that all my methods use the original account object, as it stands I'm going to have to have the same methods twice for each different type of account. This seems very inefficient and a bit tedious to change. Ideally I'd want to take a user input savings/deposit and then create the relevant object and use this repeatedly so I don't need to define all the methods twice. Just as an example here is one of my methods. To summarise I'd want this method to do the exact same thing for both account types just on different objects and the files to be named slightly differently (filname-savings.txt and filenameTransactions-savings.txt)
Is this possible or is there a better way to solve this issue?
Account account = new Account();
public void ManageAccount(String name) {
try {
File myObj = new File(name + ".txt");
if (myObj.createNewFile()) {
File myTransactionObj = new File(name + "Transactions.txt");
myTransactionObj.createNewFile();
// If File doesn't exist creates name.txt with 0 balance
writer.SingleLineWriter(name, "0");
} else {
account.setName(name);
String line = reader.SingleLineRead(name);
double balance = Double.parseDouble(line);
double newBalance = ManageBank(balance);
writer.BalanceAppender(newBalance, name);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
SavingsAccount class
public class SavingsAccount extends AbstractBankAccount implements BankAccount {
}
DepositAccount class
public class DepositAccount extends AbstractBankAccount implements BankAccount {
}
Bank Class
public class Bank {
DepositAccount account = new DepositAccount();
ScannerClass scanner = new ScannerClass();
DateManager dateManager = new DateManager();
List<Transaction> transactionsToAdd = new ArrayList<Transaction>();
Writer writer = new Writer();
Reader reader = new Reader();
public void ManageAccount(String name) {
try {
File myObj = new File(name + ".txt");
if (myObj.createNewFile()) {
File myTransactionObj = new File(name + "Transactions.txt");
myTransactionObj.createNewFile();
// If File doesn't exist creates name.txt with 0 balance
writer.SingleLineWriter(name, "0");
} else {
account.setName(name);
String line = reader.SingleLineRead(name);
double balance = Double.parseDouble(line);
double newBalance = ManageBank(balance);
writer.BalanceAppender(newBalance, name);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public void ManageAccountSavings(String name) {
try {
File myObj = new File(name + "-Savings.txt");
if (myObj.createNewFile()) {
File myTransactionObj = new File(name + "-Savings.Transactions.txt");
myTransactionObj.createNewFile();
// If File doesn't exist creates name.txt with 0 balance
writer.SingleLineWriter(name, "0");
} else {
account.setName(name);
String line = reader.SingleLineRead(name);
double balance = Double.parseDouble(line);
double newBalance = ManageBank(balance);
writer.BalanceAppender(newBalance, name);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public double ManageBank(double balance) throws IOException {
// TODO Auto-generated method stub
boolean quit = false;
List<String> transactions = reader.readPreviousTransactions(account.getName());
do {
int userChoice = scanner.InitialChoiceScanner();
switch (userChoice) {
case 1:
double amount = scanner.DepositScanner();
balance = account.Deposit(balance, amount);
System.out.print("Your new balance is: " + balance);
String depositFullDate = dateManager.getDateAsString();
Transaction depositTransaction = new Transaction("Deposit", amount, depositFullDate);
transactionsToAdd.add(depositTransaction);
break;
case 2:
double withdrawAmount = scanner.WithdrawScanner();
if (withdrawAmount > balance) {
System.out.println("Sorry not enough funds");
break;
}
balance = account.Withdraw(balance, withdrawAmount);
System.out.print("Your new balance is: " + balance);
String withdrawFullDate = dateManager.getDateAsString();
Transaction withdrawTransaction = new Transaction("Withdraw", withdrawAmount, withdrawFullDate);
transactionsToAdd.add(withdrawTransaction);
break;
case 3:
System.out.print("Your current balance is: " + balance);
break;
case 4:
writer.displayStatement(account.getName());
break;
case 0:
quit = true;
break;
default:
System.out.println("Please select a valid choice;");
break;
}
System.out.println();
} while (!quit);
String name = account.getName();
List<Transaction> parsedTransactions = writer.parseStringToTransaction(transactions);
for (Transaction transaction : parsedTransactions) {
transactionsToAdd.add(transaction);
}
writer.transactionWriter(transactionsToAdd, name);
System.out.println("Thankyou for using the banking service!");
return balance;
}
Best way is to make you Account as interface with methods those you want, and have two implementations for your Deposit and Savings accounts..
For example..
interface Account {
void setName(String name);
String getName();
void deposit(Double amount);
void updateBalance(Double balance);
Double getBalance();
}
class Deposit implements Account {
private String name;
private Double balance;
#Override
public void setName(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
#Override
public void deposit(Double amount) {
this.balance += amount;
}
#Override
public Double getBalance() {
return balance;
}
#Override
public void updateBalance(Double balance) {
this.balance = balance;
}
}
Here is my code:
import java.util.LinkedList;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.*;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list == null;
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args){
while(true){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
while (empList.hasItems()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
// int choose;
// do{
//
//
// System.out.println("\nGo back to main?<1=Yes/0=No>: \n");
// choose = sc.nextInt();
// }while (choose != 1);
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
Case 2 shows no error but when I run it on the IDE it shows:
Exception in thread "main" java.util.NoSuchElementException at
java.util.LinkedList.getFirst(Unknown Source) at
GenQueue.getFirst(something.java:44) at
something.main(something.java:113)
Any idea why this happen? and how to fix it? Your help will be very much appreciated, from python I just went Java today, newbie here.
NoSuchElementException is thrown by LinkedList.getFirst when the list is empty.
You should handle that particular case before calling that method, for example:
if (!empList.hasItems()) {
System.out.println("The queue is empty!");
} else {
System.out.println("First in queue: " +empList.getFirst());
... // rest of code
}
I finished this program and demo for my TA. I completely forgot one thing. So, the program is about hiring and firing people using stack and queues. I figured everything out except for one thing. I have to hire at least 3 people and whoever the first applicant is, I will hire them first so on. Here's the problem:
When I fire someone (The last person hired), that person should be the next person to get hired. Example:
Fired Name: b SS: 2
next person hired should be
Hired Name: b SS: 2.
I can't figure out how to get the last person fired to be the next person hired. Here's my program:
class Person {
public String name;
public String SS;
public Person(String N, String S) {
this.name = N;
this.SS = S;
}
}
class Manager {
Scanner keyboard = new Scanner(System.in);
private Queue<Person> app = new Queue<Person>();
public Stack<Person> hire = new Stack<Person>();
public Stack<Person> fire = new Stack<Person>();
public void Apply() throws QueueException {
System.out.print("Applicant Name: ");
String appName = keyboard.nextLine();
System.out.print("SSN: ");
String appSS = keyboard.nextLine();
Person apply = new Person(appName, appSS);
app.enqueue(apply);
}
public void hire() throws QueueException {
if (!app.isEmpty()) {
Person newHire = hire.push(app.dequeue());
System.out.println("Hired \nName: " + newHire.name + " SS: " + newHire.SS);
//hire.push(app.dequeue());
} else if (!fire.isEmpty()) {
Person newFire = app.dequeue();
System.out.println("Hired \nName: " + newFire.name + " SS: " + newFire.SS);
} else {
System.out.println("Nobody to hire.");
}
}
public void fire() throws StackException {
if (!hire.isEmpty()) {
Person newFire = fire.push(hire.pop());
System.out.println("Fired \nName: " + newFire.name + " SS: " + newFire.SS);
fire.push(hire.pop());
} else {
System.out.println("Nobody to fire");
}
}
}
public class Management {
public static void main(String[] args) throws QueueException, StackException {
Scanner keyboard = new Scanner(System.in);
Manager user = new Manager();
boolean test = true;
while (test) {
System.out.print("Press \n\t1 ACCEPT APPLICANT");
System.out.print("\n\t2 Hire \n\t3 Fire \n\t4 Quit:");
System.out.print("\nAnswer: \n");
int action = keyboard.nextInt();
String space = keyboard.nextLine();
if (action == 1) {
user.Apply();
} else if (action == 2) {
user.hire();
} else if (action == 3) {
user.fire();
} else if (action == 4) {
System.exit(0);
} else {
System.out.println("Please try again.");
}
}
you have this error on the hire() method.
Person newFire = app.dequeue();
you see that you are executing this line even tho app queue is Empty. just use fire stack instead of app queue.
public void hire() throws QueueException {
if (!app.isEmpty()) {
Person newHire = hire.push(app.dequeue());
System.out.println("Hired \nName: " + newHire.name + " SS: " + newHire.SS);
//hire.push(app.dequeue());
} else if (!fire.isEmpty()) {
Person newFire = fire.pop();
hire.push(newFire);
System.out.println("Hired \nName: " + newFire.name + " SS: " + newFire.SS);
} else {
System.out.println("Nobody to hire.");
}
}
How to differentiate the integer and double. Example if i wanted to get integer and verify it. if it is integer then output "YOU are correct" else "You entred wrong. try again".
import javax.swing.*;
public class InputExceptions {
private static int inputInt;
private static double inputDouble;
public static int inputInt() {
boolean inputOK = false;
while (inputOK == false) {
inputInt = Integer.parseInt(JOptionPane.showInputDialog("Enter Integer"));
try {
inputOK = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"*** ERROR: VALUE ENTERED NOT INTEGER ***");
}
} return inputInt;
}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,"*** INTEGER is correct Input: " + inputInt() + " ***");
}
}
This is the exception I am getting:
Exception in thread "main" java.lang.NullPointerException
at BankAccountDemo.DisplayAccountFees(BankAccountDemo.java:91)
at BankAccountDemo.main(BankAccountDemo.java:30)
I am also getting this exception whenever I try to print or view all the accounts with the fees assessed.
Here is my driver program. It has 5 classes, which are also below. One of them is an abstract class with 3 descendants.
DRIVER
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class BankAccountDemo
{
public static void main(String[] args)
{
while(true) {
Scanner keyboard = new Scanner(System.in);
System.out.println("=========Menu========");
System.out.println("1. Add an account.");
System.out.println("2. To print the names of all accounts together with the fees assessed");
System.out.println("3. To print all accounts together with owner information");
System.out.println("4. To exit program");
System.out.println("Your choice: ");
int input = keyboard.nextInt();
switch(input)
{
case 1:
InputAccount();
break;
case 2:
DisplayAccountFees();
break;
case 3:
ShowAccount();
break;
default:
PrintToFile();
System.exit(0);
}
}
}
private static void InputAccount()
{
System.out.println("Please enter user data as prompted...");
System.out.println("Please enter account type: Press '1' for Checking, '2' for Savings, '3' for Loan");
System.out.println("Account Type: ");
Scanner keyboard = new Scanner(System.in);
int type = keyboard.nextInt();
switch(type)
{
case 1:
{
Checking aChecking = new Checking();
aChecking.AddAccount();
checkAccounts.add(aChecking);
break;
}
case 2:
{
Savings aSavings = new Savings();
aSavings.AddAccount();
savingsAccounts.add(aSavings);
break;
}
case 3:
{
Loan aLoan = new Loan();
aLoan.AddAccount();
loanAccounts.add(aLoan);
break;
}
}
}
private static void DisplayAccountFees()
{
for (int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
Person aPerson = aSavings.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aSavings.getAcctNumber());
System.out.println("are: " + aSavings.accountFee());
}
for (int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
Person aPerson = aChecking.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aChecking.getAcctNumber());
System.out.println("are: " + aChecking.accountFee());
}
for(int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
Person aPerson = aLoan.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aLoan.getAcctNumber());
System.out.println("are: " + aLoan.accountFee());
}
}
private static void ShowAccount()
{
for(int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
aSavings.DisplayData();
}
for(int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
aChecking.DisplayData();
}
for(int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
aLoan.DisplayData();
}
}
private static void PrintToFile()
{
try
{
FileOutputStream fileOutput = new FileOutputStream("Accounts.dat");
ObjectOutputStream printFile = new ObjectOutputStream(fileOutput);
for (int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
aLoan.PrintAccountToFile(printFile);
}
for (int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
aChecking.PrintAccountToFile(printFile);
}
for (int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
aSavings.PrintAccountToFile(printFile);
}
printFile.close();
fileOutput.close();
}
catch(IOException ex)
{
}
}
private static ArrayList<Checking> checkAccounts = new ArrayList<Checking>();
private static ArrayList<Savings> savingsAccounts = new ArrayList<Savings>();
private static ArrayList<Loan> loanAccounts = new ArrayList<Loan>();
}
ACCOUNT CLASS
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public abstract class Account {
private String bankName;
private String bankAddress;
private String acctNumber;
private String acctType;
private double balance;
private Person accountHolder;
public Account()
{
}
public Person setAccountHolder(Person holder)
{
return holder;
}
public void setBankName(String newBankName)
{
bankName = newBankName;
}
public void setAddress(String newBankAddress)
{
bankAddress = newBankAddress;
}
public void setAcctNumber(String newAcctNumber)
{
acctNumber = newAcctNumber;
}
public void setBalance(double newBalance)
{
balance = newBalance;
}
public void setAcctType(String newAcctType)
{
acctType = newAcctType;
}
public Person getAccountHolder()
{
return accountHolder;
}
public String getBankName()
{
return bankName;
}
public String getAddress()
{
return bankAddress;
}
public String getAcctNumber()
{
return acctNumber;
}
public String getAcctType()
{
return acctType;
}
public double getBalance()
{
return balance;
}
public abstract double accountFee();
public abstract void DisplayData();
public abstract void AddAccount();
public abstract void PrintAccountToFile(ObjectOutputStream printFile);
public void readInputAccount()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of your bank: ");
bankName = keyboard.nextLine();
System.out.println("Enter the address of your bank: ");
bankAddress = keyboard.nextLine();
System.out.println("Enter your account number: ");
acctNumber = keyboard.nextLine();
System.out.println("Enter your current balance: ");
balance = keyboard.nextDouble();
}
public void PrintBankInfo(ObjectOutputStream printFile)
{
try
{
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Bank information: ");
printFile.writeUTF("------------------------------------------");
printFile.writeUTF("Bank name: " + getBankName());
printFile.writeUTF("Bank Address: " + getAddress());
}
catch(IOException ex)
{
}
}
public void DisplayBankInfo()
{
System.out.println("------------------------------------------");
System.out.println(" Bank information: ");
System.out.println("------------------------------------------");
System.out.println("Bank name: " + getBankName());
System.out.println("Bank Address: " + getAddress());
}
}
CHECKING CLASS
import java.util.Scanner;
import java.io.*;
public class Checking extends Account {
private double monthFee;
private int checksAllowed;
private int checksUsed;
public Checking()
{
}
public double accountFee()
{
int tooManyChecks = checksUsed - checksAllowed;
double fee = monthFee + (3.00 * tooManyChecks);
return fee;
}
public double getMonthFee()
{
return monthFee;
}
public int getChecksAllowed()
{
return checksAllowed;
}
public int getChecksUsed()
{
return checksUsed;
}
public void setMonthFee(double newMonthFee)
{
monthFee = newMonthFee;
}
public void setChecksAllowed(int newChecksAllowed)
{
checksAllowed = newChecksAllowed;
}
public void setChecksUsed(int newChecksUsed)
{
checksUsed = newChecksUsed;
}
public void AddAccount()
{
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the monthly fee: ");
monthFee = keyboard.nextDouble();
System.out.println("Please enter the number of free checks allowed: ");
checksAllowed = keyboard.nextInt();
System.out.println("Please enter the number of checks used: ");
checksUsed = keyboard.nextInt();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
DisplayBankInfo();
System.out.println("------------------------------------------");
System.out.println(" Account information: ");
System.out.println("Account Type : Checking");
System.out.println("Bank account number :" + getAcctNumber());
System.out.println("Account balance :" + getBalance());
System.out.println("Monthly fee :" + getMonthFee());
System.out.println("Number of checks used :" + getChecksUsed());
System.out.println("Number of free checks :" + getChecksAllowed());
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
PrintBankInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type : Checking");
printFile.writeUTF("Bank account number :" + getAcctNumber());
printFile.writeUTF("Account balance :" + getBalance());
printFile.writeUTF("Monthly fee :" + getMonthFee());
printFile.writeUTF("Number of checks used :" + getChecksUsed());
printFile.writeUTF("Number of free checks :" + getChecksAllowed());
printFile.writeUTF("Fees accessed : " + accountFee());
}
catch(IOException ex)
{
}
}
}
LOAN CLASS
import java.util.Scanner;
import java.io.*;
public class Loan extends Account {
private double monthPayment;
private int daysOverDue;
public Loan()
{
}
public void setMonthPayment(double newMonthPayment)
{
monthPayment = newMonthPayment;
}
public void setDaysOverDue(int newDaysOverDue)
{
daysOverDue = newDaysOverDue;
}
public double getMonthPayment()
{
return monthPayment;
}
public int getDaysOverDue()
{
return daysOverDue;
}
public double accountFee()
{
double fee = 0.001 * monthPayment * daysOverDue;
return fee;
}
public void AddAccount(){
Scanner keyboard = new Scanner(System.in);
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
System.out.println("Please enter the monthly payment amount: ");
monthPayment = keyboard.nextDouble();
System.out.println("Please enter the number of days past the grace period: ");
daysOverDue = keyboard.nextInt();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type: Loan");
printFile.writeUTF("Bank account number: " + getAcctNumber());
printFile.writeUTF("Account balance: " + getBalance());
printFile.writeUTF("Monthly payment amount: " + getMonthPayment());
printFile.writeUTF("Number of days past the grace period: " + getDaysOverDue());
printFile.writeUTF("Fees assessed: " + accountFee());
}
catch(IOException ex)
{
}
}
}
SAVINGS CLASS
import java.io.*;
import java.util.Scanner;
public class Savings extends Account {
private double minBal;
private double intRate;
private double avgBal;
public Savings()
{
}
public double accountFee()
{
double fee = 0.00;
if (avgBal < minBal)
{
fee = 50.00;
}
return fee;
}
public double getMinBal()
{
return minBal;
}
public double getIntRate()
{
return minBal;
}
public double getAvgBal()
{
return avgBal;
}
public void setMinBal(double newMinBal)
{
minBal = newMinBal;
}
public void setIntRate(double newIntRate)
{
minBal = newIntRate;
}
public double getChecks()
{
return intRate;
}
public void setChecks(double newIntRate)
{
intRate = newIntRate;
}
public void setAvgBal(double newAvgBal)
{
avgBal = newAvgBal;
}
public void AddAccount()
{
Scanner keyboard = new Scanner(System.in);
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
System.out.println("Please enter the minimum balance: ");
minBal = keyboard.nextDouble();
System.out.println("Please enter the average balance: ");
avgBal = keyboard.nextDouble();
System.out.println("Please enter interest rate");
intRate = keyboard.nextDouble();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
DisplayBankInfo();
System.out.println("------------------------------------------");
System.out.println(" Account information: ");
System.out.println("Account Type: Savings Account");
System.out.println("Bank account number: " + getAcctNumber());
System.out.println("Account balance: " + getBalance());
System.out.println("Minimum balance: " + getMinBal());
System.out.println("Average balance: " + getAvgBal());
System.out.println("Interest rate: " + getIntRate());
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
PrintBankInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type: Savings Account");
printFile.writeUTF("Bank account number: " + getAcctNumber());
printFile.writeUTF("Account balance: " + getBalance());
printFile.writeUTF("Minimum balance: " + getMinBal());
printFile.writeUTF("Average balance: " + getAvgBal());
printFile.writeUTF("Interest rate: " + getIntRate());
printFile.writeUTF("Fees assessed: " + accountFee());
}
catch(IOException ex)
{
}
}
}
The problem is that your setAccountHolder method doesn't actually set anything:
Instead of:
public Person setAccountHolder(Person holder)
{
return holder;
}
it should be:
public void setAccountHolder(Person holder) {
this.accountHolder = holder;
}
1.) Where do you initialize savingsAccounts attribute?
2.) When you do
DisplayAccountFees()
you start by doing
Savings aSavings = savingsAccounts.get(n);
are you sure that get(n) always returns data?