Array List Average - java

I'm trying to figure out how to get the Max & Min accounts to also print prints its account number, balance and average transaction amount.
I've tried all sorts of garb and have gotten nowhere.
import java.util.ArrayList;
import java.util.Scanner;
public class BankAccount {
private int AccountNumber;
public int getAccountNumber()
{
return AccountNumber;
}
private double Balance;
public double getBalance()
{
return Balance;
}
private ArrayList<Double> transactions = new ArrayList<Double>();
public void Deposit(double Balance)
{
transactions.add(Balance);
this.Balance = this.Balance + Balance;
}
public void Withdraw(double Balance)
{
transactions.add(-Balance);
this.Balance = this.Balance - Balance;
}
public BankAccount(int initialAccountNumber, double initialBalance)
{
this.Balance = initialBalance;
this.AccountNumber = initialAccountNumber;
transactions.add(initialBalance);
}
public double getAverage()
{
double sum = 0;
for (double element : transactions)
{
sum = sum + Math.abs(element);
}
double Average = sum / transactions.size();
return Average;
}
}
---
import java.util.ArrayList;
public class Bank {
private ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
public void MakeAccount(int initialAccountNumber, double initialBalance)
{
BankAccount NewAcc = new BankAccount(initialAccountNumber, initialBalance);
accounts.add(NewAcc);
}
public BankAccount FindLarAcc(int initialAccountNumber, double initialBalance)
{
BankAccount largest = accounts.get(0);
for (int i = 1; i < accounts.size(); i++)
{
BankAccount a = accounts.get(i);
if (a.getBalance() > largest.getBalance())
largest = a;
}
return largest;
}
public BankAccount FindLowAcc(int initialAccountNumber, double initialBalance)
{
BankAccount smallest = accounts.get(0);
for (int i = 1; i < accounts.size(); i++)
{
BankAccount a = accounts.get(i);
if (a.getBalance() < smallest.getBalance())
smallest = a;
}
return smallest;
}
public BankAccount FindAcc(int initialAccountNumber)
{
for (BankAccount a: accounts)
{
if (a.getAccountNumber() == initialAccountNumber)
return a;
}
return null;
}
}
---
import java.util.Scanner;
public class BankTester {
public static void main(String[] args){
Scanner in = new Scanner (System.in);
/**int AccountNumber = 0;*/
double Balance = 0;
double Amount = 0;
Bank Bank1 = new Bank();
boolean done = false;
while (!done)
{
System.out.println("Enter an Account Number to begin, enter -1 to quit: ");
int AccountNumber = in.nextInt();
if (AccountNumber == -1)
{
done = true;
} else {
System.out.println("Now enter a Balance: ");
Balance = in.nextDouble();
Bank1.MakeAccount(AccountNumber, Balance);
BankAccount B = Bank1.FindAcc(AccountNumber);
System.out.println("How much would you like to deposit? ");
Amount = in.nextDouble();
B.Deposit(Amount);
System.out.println("How much would you like to withdrawl? ");
Amount = in.nextDouble();
B.Withdraw(Amount);
}
BankAccount Max = Bank1.FindLarAcc(AccountNumber, Balance);
BankAccount Min = Bank1.FindLowAcc(AccountNumber, Balance);
/**
* Print & Compute Average
*/
System.out.println("Account " + Min.getAccountNumber() +
" has the smallest balance. ");
System.out.println("Account " + Max.getAccountNumber() +
" has the largest balance. ");
}
}
}

For those who might have had the same problem...I figured it out!
This belongs on the BankTester class, btw
System.out.println("Account " + Min.getAccountNumber() +
" has the smallest balance of, " + Min.getBalance() +
" and a average transaction of, " + Min.getAverage());
System.out.println("Account " + Max.getAccountNumber() +
" has the largest balance of, " + Max.getBalance() +
" and a average transaction of, " + Max.getAverage());

Related

How do I search or access an account I made in my banking system program?

I'm working on a baking system program for a school project which includes the ff. features:
Creating a new account
Balance Inquiry
Deposit
Withdraw
Close account
So far here's the code I've written:
class BankAccountAndaya {
private String accountName, address, birthday, contactNumber;
Scanner sc = new Scanner(System.in);
//default constructor
public BankAccountAndaya() {
}
public BankAccountAndaya(String accountName, String address, String birthday, String contactNumber){
this.accountName = accountName;
this.address = address;
this.birthday = birthday;
this.contactNumber = contactNumber;
}
//accessor
public String getAccountName() {
return accountName;
}
public String getAddress() {
return address;
}
public String getBirthday() {
return birthday;
}
public String getContactNumber() {
return contactNumber;
}
//mutators
public void setAccountName(String name) {
this.accountName = name;
}
public void setAddress(String address) {
this.address = address;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setContactNumber(String contactNum) {
this.contactNumber = contactNum;
}
public void getClientDetails() {
System.out.print("Enter name: ");
setAccountName(sc.next());
System.out.print("Enter address: ");
setAddress(sc.next());
System.out.print("Enter birthday (MM/DD/YY): ");
setBirthday(sc.next());
System.out.print("Enter contact number: ");
setContactNumber(sc.next());
}
}
public class SavingsAccountAndaya extends BankAccountAndaya {
private int accountNo;
private double balance, interestRate;
Random rd = new Random();
Scanner sc = new Scanner(System.in);
// default constructor
SavingsAccountAndaya() {
}
// accessors
public int getAccountNo() {
return accountNo;
}
public double getBalance() {
return balance;
}
public double getInterestRate() {
return interestRate;
}
// mutators
public void setAccountNo(int acctNo) {
this.accountNo = acctNo;
}
public void setBalance(double bal) {
this.balance = bal;
}
public void setInterestRate(double intR) {
this.interestRate = intR;
}
public boolean validateAcctNumber(int search) {
for (int i = 0; i < 100; i++) {
int listVal = getAccountNo();
if (search == listVal) {
return true;
}
}
return false;
}
public void balanceInquiry() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.println("Client name: " + getAccountName());
System.out.println("Balance: " + getBalance());
} else {
System.out.println("Account number invalid!");
}
}
public void deposit() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.print("Enter amount to deposit: ");
double deposit = sc.nextDouble();
if (deposit >= 100) {
balance += deposit;
interestRate = 0.05 * balance;
balance += interestRate;
System.out.println("Amount deposit successful!");
System.out.println("Updated balance: " + balance);
} else {
System.out.println("Invalid deposit number!");
}
} else {
System.out.println("Invalid account number!");
}
}
public void withdraw() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.print("Enter amount to withdraw: ");
double withdraw = sc.nextDouble();
double mainBal = withdraw - balance;
if (withdraw >= 100 && withdraw < balance && mainBal >= 5000) {
balance -= withdraw;
System.out.println("Amount withdrawn successful!");
System.out.println("Updated balance: " + balance);
} else {
System.out.println("Invalid withrawal amount!");
}
} else {
System.out.println("Invalid account number!");
}
}
public void closeAccount() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
setAccountNo(0);
setBalance(0);
setAccountName("");
setAddress("");
setBirthday("");
setContactNumber("");
} else {
System.out.println("Invalid account number!");
}
}
}
public class ClientAndaya extends SavingsAccountAndaya {
/**
* #param args the command line arguments
*/
public static void displayMainMenu() {
System.out.println("JBank Main Menu");
System.out.println("[1] New Account");
System.out.println("[2] Balance Inquiry");
System.out.println("[3] Deposit");
System.out.println("[4] Withdraw");
System.out.println("[5] Client Profile");
System.out.println("[6] Close Account");
System.out.println("[7] Exit");
}
public static void main(String[] args) {
int i = 0;
SavingsAccountAndaya[] sa = new SavingsAccountAndaya[100];
Random rd = new Random();
Scanner sc = new Scanner(System.in);
int input;
do {
displayMainMenu();
System.out.print("Enter number: ");
input = sc.nextInt();
sa[i] = new SavingsAccountAndaya();
switch (input) {
case 1:
System.out.println("New Account: ");
sa[i].getClientDetails();
System.out.print("Enter amount to deposit: ");
double inDepo = sc.nextDouble();
if (inDepo < 5000) {
System.out.println("Invalid initial deposit amount!");
System.out.println("Amount must be greater than 5000 PHP");
System.out.print("Enter amount to deposit: ");
inDepo = sc.nextDouble();
}
sa[i].setBalance(inDepo);
// generate account number
int ranNo = rd.nextInt(9999);
sa[i].setAccountNo(ranNo);
System.out.println("Account number: " + sa[i].getAccountNo());
i++;
break;
case 2:
System.out.println("Balance Inquiry: ");
sa[i].balanceInquiry();
break;
case 3:
System.out.println("Deposit: ");
sa[i].deposit();
break;
case 4:
System.out.println("Withdraw: ");
sa[i].withdraw();
break;
case 5:
System.out.println("Client Profile: ");
System.out.println("Account number: " + sa[i].getAccountNo());
System.out.println("Accoutn Name: " + sa[i].getAccountName());
System.out.println("Address: " + sa[i].getAddress());
System.out.println("Birthday: " + sa[i].getBirthday());
System.out.println("Contact Number: " + sa[i].getContactNumber());
System.out.println("Balance: " + sa[i].getBalance());
break;
case 6:
System.out.println("Close Account: ");
sa[i].closeAccount();
break;
case 7:
break;
default:
System.out.println("Invalid chosen number!");
}
} while (input < 6 && input > 0);
}
}
I can't seem to access or search for an account I've created. Whenever I input the account number, it always results to invalid account number even though I've already created an account that has that account number. I think the problem lies with the validateAcctNumber method:
public boolean validateAcctNumber(int search) {
for (int i = 0; i < 100; i++) {
int listVal = getAccountNo();
if (search == listVal) {
return true;
}
}
return false;
}
It was also mentioned in the instructions to use exception to validate inputs.
How can I solve this problem? Thank you for your help.

Handle Scanner exception on Java program

I am working on a school project. I have all the functionality working but when I submit the project through Mimir, during deposits and withdraws it gives the following error:
Enter the amount you want to Deposit :$Exception in thread "main" java.util.NoSuchElementException
13 at java.util.Scanner.throwFor(Scanner.java:862)
14 at java.util.Scanner.next(Scanner.java:1485)
15 at java.util.Scanner.nextDouble(Scanner.java:2345)
16 at BankAccount.deposit(BankAccount.java:24)
17 at SavingsAccountDemo.main(SavingsAccountDemo.java:30)
The project does says the following: Please make sure that your classes throw appropriate exceptions when an attempt is made to insert invalid data.
I tried to add the try and catch with java.util.InputMismatchException e but it doesn't seem to be fixing it. I think it's because the userInput is a double and they are entering something different. Any ideas how can I fix that? Here is the code:
///SavingsAccountDemo class
import java.util.*;
public class SavingsAccountDemo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double startingBalance;
double interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextDouble();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextDouble();
double bal = startingBalance;
double rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
BankDemo sv = new BankDemo(bal, rate);
while(startingBalance > -1) {
try {
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else if("e".equals(userInput)) {
ba.exit();
break;
}
else {
System.out.print("Error, option not valid\n");
}
}
catch (java.util.InputMismatchException e) {
System.out.print("Error");
}
}
}
}
///BankAccount class
import java.util.*;
public class BankAccount {
protected double balance;
protected double numDeposits;
protected double numWithdrawals;
protected double annualRate;
protected double monthlyServCharg;
protected boolean active;
Scanner keyboard = new Scanner(System.in);
public BankAccount(double startingBalance, double interestRate) {
balance = startingBalance;
annualRate = interestRate /= 100.0;
if(balance < 25) {
active = false;
} else
active = true;
}
public void deposit() {
try {
double valueD;
System.out.print("Enter the amount you want to Deposit :$");
valueD = keyboard.nextDouble();
if(valueD < 0) {
System.out.println("Error: Must enter positive value\n");
}
if( balance + valueD >= 25 && !active) {
System.out.print("Your account is now ACTIVE\n");
active = true;
}
balance += valueD;
numDeposits++;
}
catch (java.util.InputMismatchException e){
keyboard.nextLine();
}
}
public void withdraw() {
try {
double valueW;
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextDouble();
if(valueW < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numWithdrawals++;
if(balance < 0) {
System.out.print("ERROR: Transaction declined!! This transaction will cause overdraft or zero balance\n");
balance += valueW;
} else if(balance <= 25 && active) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
active = false;
}
if(numWithdrawals > 4) {
balance --;
System.out.print("You have exceeded monthly limit of withdrawals. Fee of $1 charged\n");
}
}
catch (java.util.InputMismatchException e) {
keyboard.nextLine();
}
}
public void totalBalance() {
System.out.printf("Your Balance is: %.2f\n", balance);
}
public void calcInterest() {
double monRate = annualRate / 12;
double monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f\n", balance);
}
public void exit() {
totalBalance();
System.out.print("Thank you. Bye");
}
}

Calling Methods (Java)

Summary, I am to write a class called BankAccount and my professor has provided me with a driver.
Here is my class so far:
import java.util.Date;
public class BankAccount implements AccountInterface
{
private double balance;
private String name;
private Date creationDate = new Date ();
private boolean frozen;
private double limit;
private final double MAXLIMIT = 500;
private int accountNumber;
private static int howMany;
public BankAccount( )
{
this.name = "Classified";
this.creationDate.getTime();
this.frozen = false;
this.limit = 300;
this.howMany++;
this.accountNumber = howMany;
this.balance = 0;
}
public BankAccount (String creationName)
{
this.name = creationName;
this.creationDate.getTime();
this.frozen = false;
this.limit = 300;
this.howMany++;
this.accountNumber = howMany;
this.balance = 0;
}
public static int getNumAccounts ( )
{
return howMany;
}
public void deposit(double theMoney)
{
if (frozen = true)
throw new IllegalStateException ("Cannot Deposit - Account Is Frozen");
else if (theMoney < 0)
throw new IllegalArgumentException("Insufficient funds");
else
balance = balance + theMoney;
}
public double withdraw(double theMoney)
{
if (theMoney < 0 || balance == 0 || theMoney > limit || theMoney % 20 !=0)
throw new IllegalArgumentException ("There was an error in your withdraw.");
else if (frozen = true)
throw new IllegalStateException ("Cannot Deposit - Account Is Frozen");
else
balance = balance - theMoney;
return balance;
}
public double getBalance()
{
return balance;
}
public void freeze()
{
frozen = true;
}
public void unfreeze()
{
frozen = false;
}
public void setLimit(double newLimit)
{
if (newLimit < 0 || newLimit > MAXLIMIT)
throw new IllegalArgumentException ("There was a limit error.");
else if (frozen = true)
throw new IllegalStateException ("Cannot Deposit - Account Is Frozen");
else
limit = newLimit;
}
public double getLimit( )
{
return limit;
}
public String toString( )
{
return "\nAccount number: " + accountNumber + "\nName: " + name + "\nCreation Date: " + creationDate + "\nBalance: " + balance + "\nWithdrawal Limit: " + limit ;
}
}
The problem that I am running into is when the driver calls myAccount.unfreeze(); in my class it does not set the account to unfreeze. So When the driver goes to deposit any money my class returns Cannot Deposit - Account Is Frozen even though I have a method called unfreeze. I thought at first I might have missed spelled frozen or unfreeze wrong, but that is not the case. Hopefully, some fresh pair of eyes can spot something that I am skipping over.
Thank you for your help!
When you use single equation sign, you are assigning the value. Use double equal sign to check for equality. In your case you should be using if(frozen==false) and if(frozen==true) whenever you are checking for its value.

Bank Account Java Program

I am creating a bank account program for my java class that is suppose to manage up to 5 different bank accounts. The program has to allow the creation of a new account, which I have done, allow deposit and withdraw, which is also done, the 2 parts I cannot get to work are 1: the bank can only have up to 5 accounts, so if a 6th is trying to be created, a message comes up saying that 5 are already created, and 2: one of the options has to print out all the account balances of current accounts in the bank.
This is my code as of now:
import java.util.Scanner;
public class Bankapp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print account balance");
System.out.println("5) Quit");
System.out.println();
System.out.print("Enter choice [1-5]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1:
System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
case 5:
System.out.println("Here are the balances " + "for each account:");
case 6:
System.exit(0);
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts = 5; // the number of bank accounts at this bank
// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[5];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
}
public int getAccountNum(){
return accountNum;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
}
}
}
}//end of class
The program runs fine, I just need to add these two options, and cannot get them to work properly, how would I go about doing this? Also, options 3 and 4 should not work if no accounts have been created yet. Thanks in advance.
UPDATE: this is what I tried, I keep getting a this method must return type int error.
public int openNewAccount(String customerName, double openingBalance) {
if(numOfAccounts > 5)
{
System.out.println("5 accounts already exist");
}
else
{
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
}
UPDATE 2: I added a return statement, now when it runs it will open accounts up to number 5, but for every account after number 5 it just says the account number is 5 again instead of not opening an account.
public int openNewAccount(String customerName, double openingBalance) {
if(numOfAccounts > 5)
{
System.out.println("5 accounts already exist");
}
else
{
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
return numOfAccounts;
}
Its pretty simple. Create a list of size 5 and add the account into that list when user is created one. Before adding just make a check whether list size <= 5. If it is true, go ahead and add the account, otherwise throw an error
For option 2, just iterate through the list and display the results
1; in the openNewBank account method; before creating the new Bank account and increasing the count by 1; check if the number of account is already at 5 or higher and if it is dont create the account and dont increase the count.
2: Loop through the number of account variable and print.
I added password system to it. and nice looking account num.
Code :
import java.io.*;
import java.util.Random;
public class Computer_Bank_of_India {
public static int NewRandom(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String args[])throws IOException, InterruptedException {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
Bank myBank = new Bank();
int Option = 1, Account_Number, Account_Password, atempts = 0, Pass;
String Name;
double Balance, Money;
System.out.println("Please wait, the system is starting...");
while(Option !=5) {
Thread.sleep(4000);
System.out.println("1) Open a new bank account");
Thread.sleep(250);
System.out.println("2) Deposit to a bank account");
Thread.sleep(250);
System.out.println("3) Withdraw to bank account");
Thread.sleep(250);
System.out.println("4) Print the detailed account information including last transactions");
Thread.sleep(250);
System.out.println("5) Quit");
System.out.println();
System.out.print(" Enter Option [1-5]: ");
Option = Integer.parseInt(br.readLine());
switch(Option) {
case 1 : System.out.println("Enter a customer name :");
Name = br.readLine();
System.out.println("Enter a opening balance :");
Balance = Double.parseDouble(br.readLine());
Thread.sleep(250);
System.out.println("Creating your account....");
Thread.sleep(500);
int[] arrDetails= myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + arrDetails[0]+"\nYour password : "+ arrDetails[1]);
break;
case 2 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
System.out.println("Enter a deposit amount :");
Money = Double.parseDouble(br.readLine());
myBank.Deposit(Account_Number, Account_Password, Money);
break;
case 3 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
System.out.println("Enter a deposit amount :");
Money = Double.parseDouble(br.readLine());
myBank.Withdraw(Account_Number, Account_Password, Money);
break;
case 4 : System.out.println("Enter a account number :");
Account_Number = Integer.parseInt(br.readLine());
System.out.println("Enter a account password :");
Account_Password = Integer.parseInt(br.readLine());
myBank.Transactions(Account_Number, Account_Password);
break;
case 5 : System.out.println("Please Enter your password :");
Pass = Integer.parseInt(br.readLine());
if(Pass == myBank.Password) {
System.out.println(" System shutting down.....");
Option = 5;
break;
}
else {
Thread.sleep(250);
System.out.println("You have enter a wrong password. Please try again");
Option = 0;
}
default: System.out.println("Invalid option. Please try again.");
}
}
}
static class Bank {
private int Password=2684;
private BankAccount[] accounts;
private int numOfAccounts;
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
public int [] AddNewAccount(String Name, Double Balance) {
BankAccount b = new BankAccount(Name, Balance);
accounts[numOfAccounts] = b;
numOfAccounts++;
int Acc = b.getAccountNum()[0];
int Pass = b.getAccountNum()[1];
int[]details = {Acc, Pass};
return details;
}
public void Withdraw(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
accounts[i].withdraw(Money);
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
public void Deposit(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
accounts[i].deposit(Money);
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
public void Transactions(int Account_Number, int pass) {
for(int i = 0;i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
if (Account_Number == a ) {
int p = accounts[i].getAccountNum()[1];
if( pass == p) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(" Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
}
}
}
System.out.println(" You have entered a wrong Account number or Password.");
}
}
static class BankAccount{
private int User_Password;
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private String[] transactionsSummary;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return " Account number: " + accountNum + "\n Customer Name: " + customerName + "\n Balance:" + balance +"\n";
}
public String getTransactionInfo(int n) {
String transaction = transactionsSummary[n];
return transaction;
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
User_Password = NewRandom(1000, 9999);
accountNum = NewRandom(800000000, 999999999);
transactions = new double[100];
transactionsSummary = new String[100];
transactions[0] = balance;
transactionsSummary[0] = "A balance of : Rs" + Double.toString(balance) + " was deposited.";
numOfTransactions = 1;
}
public int [] getAccountNum(){
int account = accountNum;
int Pass = User_Password;
int [] details = {account, Pass};
return details;
}
public int getNumberOfTransactions() {
return numOfTransactions;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "Rs." + Double.toString(amount) + " was deposited.";
numOfTransactions++;
System.out.println(" Amount deposited successfully");
}
}
public void withdraw(double amount) {
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else {
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "Rs." + Double.toString(amount) + " was withdrawn.";
numOfTransactions++;
System.out.println(" Amount Withdrawn successfully");
}
}
}
}
}

Polymorphism and instanceof

I have programed a Worker and MachineWorker class. It complies fine. but when i run it, after three consecutive statements the program stops. I cannot find the problem, and I dont know how and when to use 'instanceof'.
I am writing the question below and with all the classes...
Question:- (i)Declare an array that can store the references of up to 5 Worker or MachineWorker objects.
a)Allow user to enter the type of object and the data for that type of object(3 values for Worker and 4 values for MachineWorker).
b)Construct the appropriate object storing the reference in the common array.
ii)Now allow the users to enter the weekly data repeatedly. If it is Worker object user must enter ID and hours-worked. If it is a MachineWorker object user must enter ID,hoursWorked and pieces. Once these values read search through the array to locate the object with the given ID before calling the addWeekly().The number of arguments either(1 or 2) to be passed to addWeekly depends on the type of objects being referred. To determine the type of object being referred(Worker or MachineWorker)you may use the instanceof operator.
Please see my codes below:-
//Worker.java
public class Worker {
public final double bonus=100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked,tax,grossSalary,netSalary;
public Worker(){
}
public Worker(String name, String workerID, double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double hoursWorked){
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross(){
grossSalary = (totalHoursWorked*hourlyRate);
if(totalHoursWorked>=150){
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double netAndTax(){
netSalary = grossSalary;
if(grossSalary>500){
tax = (grossSalary - 500) *0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName(){
return this.name;
}
public String getWorkerID(){
return this.workerID;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public double getTotalHours(){
return totalHoursWorked;
}
public double getGrossSalary(){
return grossSalary;
}
public void addToGross(double amt){
grossSalary = grossSalary + amt;
}
public void displaySalary(){
System.out.print("Name: " +getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate()+ "\nTotalHours Worked" + getTotalHours() +
"\nGross pay" + getGrossSalary() + "\nTax: " + netAndTax() +
"\nNet Pay: " + netAndTax());
}
}
//MachineWorker.java
public class MachineWorker extends Worker{
private double targetAmount;
private double totalPieces, productivityBonus;
public MachineWorker(String workerName, String workerID, double hourlyRate, double targetAmount)
{
super(workerName, workerID, hourlyRate);
//this.productivityBonus = productivityBonus;
this.targetAmount = targetAmount;
}
public void addWeekly(double hoursWorked, double weeklyAmount)
{
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus()
{
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross()
{
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if(totalHoursWorked >= 150)
{
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt)
{
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name " + super.name + "\nID " +
super.workerID + "\nHourly rate " + super.hourlyRate + "\nTotal Hours Worked " +
super.totalHoursWorked + "\nGross Pay $" + super.grossSalary + "\nTax $" + super.tax + "\nNetpay $" + super.netSalary);
System.out.println("Productivity Bonus " + productivityBonus);
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Worker[] a = new Worker[5];
MachineWorker[] b = new MachineWorker[5];
char option = '0';
String choice;
boolean nChar = false;
for (int i = 0; i < 5; i++){
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1)
{
option = choice.charAt(0); //pick the first character
if (option == 'w' || option == 'W')
{
System.out.println("\n\tEnter name, ID and hours: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
a[i] = new Worker(name, id, hours);
System.out.println();
}
if (option == 'm' || option == 'M')
{
System.out.print("\n\tEnter name, ID, hours and pieces: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
System.out.print(" ");
double pieces = input.nextDouble();
b[i] = new MachineWorker(name, id, hours, pieces);
System.out.println();
}
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
}
a[i].displaySalary();
b[i].displaySalary();
b[i].productivityBonus();
}
}
}
You might want to use overriden methods readfromInput and displaySalary to distinguish between what Worker and Machinworker does.
The different behaviour should be implemented within the classes and not in the calling Polyworker class.
If Machineworker displaySalary shows the bonus this should be called in displaySalary of MachineWorker
see modified code below
//Worker.java
import java.util.Scanner;
/**
* a generic worker
*/
public class Worker {
public final double bonus = 100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked, tax, grossSalary, netSalary;
public void addWeekly(double hoursWorked) {
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate);
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + 100;
}
return grossSalary;
}
public double netAndTax() {
netSalary = grossSalary;
if (grossSalary > 500) {
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName() {
return this.name;
}
public String getWorkerID() {
return this.workerID;
}
public double getHourlyRate() {
return this.hourlyRate;
}
public double getTotalHours() {
return totalHoursWorked;
}
public double getGrossSalary() {
return grossSalary;
}
public void addToGross(double amt) {
grossSalary = grossSalary + amt;
}
public void displaySalary() {
System.out.print("Name: " + getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate() + "\nTotalHours Worked"
+ getTotalHours() + "\nGross pay" + getGrossSalary() + "\nTax: "
+ netAndTax() + "\nNet Pay: " + netAndTax());
}
public void readFromInput(Scanner input) {
name = input.nextLine();
System.out.print(" ");
this.workerID= input.nextLine();
System.out.print(" ");
this.totalHoursWorked = input.nextDouble();
System.out.println();
}
} // Worker
//MachineWorker.java
import java.util.Scanner;
public class MachineWorker extends Worker {
private double targetAmount;
private double totalPieces, productivityBonus;
public void addWeekly(double hoursWorked, double weeklyAmount) {
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus() {
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt) {
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
#Override
public void displaySalary() {
super.displaySalary();
System.out.println("Productivity Bonus " + productivityBonus);
}
#Override
public void readFromInput(Scanner input) {
super.readFromInput(input);
this.totalPieces = input.nextDouble();
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Worker[] workers = new Worker[5];
char option = '0';
String choice;
for (int i = 0; i < 5; i++) {
System.out.print("\tType of object " + (i + 1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1) {
option = choice.toLowerCase().charAt(0); // pick the first character
switch (option) {
case 'w': {
workers[i] = new Worker();
System.out.println("\n\tEnter name, ID and hours: ");
}
break;
case 'm': {
System.out.print("\n\tEnter name, ID, hours and pieces: ");
}
break;
} // switch
workers[i].readFromInput(input);
}
workers[i].displaySalary();
}
}
}
Your question states that you have to store the references in a common array, where as you are storing them in 2 different arrays a and b. As you have different arrays for different type of objects, you don't have the need to use instanceOf operator. More about instanceOf is here.
Also, you do not check for null while printing salary or bonus. As at any point of the loop, only one type of object will be created, one of a[i] or b[i] will be definitely null, causing a NullPointerException.
You need another loop after the one you have already written that will allow the user to input the worker's hours. This will presumably be a while loop that will continually ask for input. You would then choose some sort of input that would quit the loop. Inside the loop you ask for hours and take either 2 or 3 arguments.
At the moment you are not storing your Workers/MachineWorkers. You need to create an array to store them in. You also need to create either a base class or an interface that they will both extend/implement. This will allow you to create a single array to store them all.
You then loop through your array of Workers/MachineWorkers and when you find a matching id you use your instanceof to work out whether you need to pass 1 or 2 arguments. If it is a MachineWorker you should cast it as such and then call the appropriate method with 2 arguments.

Categories

Resources