Bank cash (deposit and withdrawal) - for educational purposes - java

i have a problem on my program. and my problem is that i cannot minus my withdrawal from my deposit value.
code below:
public static void main(String[] args) {
double cash;
boolean more = true;
Deposite dep = new Deposite();
Withdraw with = new Withdraw();
while (more) {
cash = Double.parseDouble(JOptionPane.showInputDialog("Cash Deposite"));
dep.Deposite(cash);
dep.print();
int con = JOptionPane.YES_NO_OPTION;
int con1 = JOptionPane.showConfirmDialog(null, "Do you want more Deposites?","DEPOSITORY",con);
if (con1 == 1) {
int con3 = JOptionPane.showConfirmDialog(null, "Withdraw now?","WITHDRAWAL",con);
if (con3 == 0) {
cash = Double.parseDouble(JOptionPane.showInputDialog("Cash Withdraw"));
with.Withdraw(cash);
with.print();
System.out.println("Thanks");
}
}
}
}
and this is my subclass that i have made for its functions
public class Deposite {
private double depcash;
public double Deposite(double cash){
depcash += cash;
return this.depcash;
}
void print(){
System.out.printf("Your deposite is $%5.2f",depcash);
System.out.println(" ");
}
}
and this is for my withdrawal class. i inherit it. but i still dont know how it works.
code below :
public class Withdraw extends Deposite {
double cash;
public double Withdraw(double withdraw){
super.Deposite(withdraw);
cash -=withdraw;
return cash;
}
void print (){
System.out.printf("You Cash Balance now is $%5.2f",cash);
System.out.println(" ");
}
}

First of all, never name your methods like object constructors
public double Deposite(double cash).
Secondly, why would your Withdraw class extend Deposite? Is there any reason for this?
That is how I would implement some banking logic:
Bank bank = new Bank();
Account account = new Account(123.50);
bank.execute(account, new Deposit(), 1);
bank.execute(account, new Withdraw(), 13.50);
private static interface Operation {
double apply(Account account, double value);
}
private static class Deposit implements Operation {
#Override
public double apply(Account account, double value) {
return account.getMoney() - value;
}
}
private static class Withdraw implements Operation {
#Override
public double apply(Account account, double value) {
return account.getMoney() + value;
}
}
private static class Account {
private final double money;
public Account(double money) {
this.money = money;
}
public double getMoney() {
return money;
}
}
private static class Bank {
public void execute(Account account, Operation operation, double amount) {
operation.apply(account, amount);
}
}

Your program have some basic problem here is the code:::
You should have made the single account for deposit and withdraw. That was your basic mistake.
import javax.swing.JOptionPane;
public class Bank {
public static double totalCash = 0;
public static void main(String[] args) {
boolean more = true;
Deposite dep = new Deposite();
Withdraw with = new Withdraw();
while (more) {
double cash = Double.parseDouble(JOptionPane.showInputDialog("Cash Deposite"));
dep.depositeCash(cash);
dep.print();
int con = JOptionPane.YES_NO_OPTION;
int con1 = JOptionPane.showConfirmDialog(null, "Do you want more Deposites?", "DEPOSITORY", con);
if (con1 == 1) {
int con3 = JOptionPane.showConfirmDialog(null, "Withdraw now?", "WITHDRAWAL", con);
if (con3 == 0) {
cash = Double.parseDouble(JOptionPane.showInputDialog("Cash Withdraw"));
with.withdrawCash(cash);
with.print();
System.out.println("Thanks");
more = false;
}
}
}
}
}
class Withdraw {
public double withdrawCash(double withdraw) {
Bank.totalCash -= withdraw;
return Bank.totalCash;
}
void print() {
System.out.printf("You Cash Balance now is $%5.2f", Bank.totalCash);
System.out.println(" ");
}
}
class Deposite {
public double depositeCash(double cash) {
Bank.totalCash += cash;
System.out.println(Bank.totalCash);
return Bank.totalCash;
}
void print() {
System.out.printf("Your deposite is :" + Bank.totalCash);
System.out.println(" ");
}
}

When you do
Deposite dep = new Deposite();
Withdraw with = new Withdraw();
it creates two different instances. One of Deposite and one of Withdraw.
You assume that both instances share the same double cash , but they don't.
If you want to start with something simple you could do something like :
import javax.swing.JOptionPane;
public class Cash {
private double depcash;
public double deposite(double cash){ //stick to java naming conventions
depcash += cash;
return depcash;
}
public double withdraw(double withdraw){
return deposite(- withdraw);
}
void print(){
//wrong - System.out.printf("Your deposite is $%5.2f",depcash);
System.out.printf("Your cash balance is $%5.2f",depcash);
System.out.println(" ");
}
public static void main(String[] args) {
double sum;
boolean more = true;
Cash cash = new Cash();
while (more) { //how do you stop ? what makes more false ?
sum = Double.parseDouble(JOptionPane.showInputDialog("Cash deposite"));
cash.deposite(sum);
cash.print();
int con = JOptionPane.YES_NO_OPTION;
int con1 = JOptionPane.showConfirmDialog(null, "Do you want more Deposites?","DEPOSITORY",con);
if (con1 == 1) {
int con3 = JOptionPane.showConfirmDialog(null, "Withdraw now?","WITHDRAWAL",con);
if (con3 == 0) {
sum = Double.parseDouble(JOptionPane.showInputDialog("Cash Withdraw"));
cash.withdraw(sum);
cash.print();
System.out.println("Thanks");
}
}
}
}
}

Related

compareAndSet() does not work as expected

I wrote my own AtomicDouble class and I also have a BankAccount class that does two simple withdrawals and deposits operations and it has an AtomicDouble instance(balance). The problem with my code is that when I call the addAndGet method in deposit(), the program falls into an infinite loop, and compareAndSet() never returns the true value, but when I debugged this, currentValue and the value from atomic.get () were equal, but this method does not understand.
The interesting thing is that when I put if (atomic.get()==currentValue) instead of if (atomic.compareAndSet(currentValue, nextValue)), the program runs properly.
public class AtomicDouble extends Number {
private final AtomicReference<Double> atomic;
public AtomicDouble() {
this(0.0);
}
public AtomicDouble(double initialValue) {
atomic = new AtomicReference<>(initialValue);
}
public final double addAndGet(double delta) {
while (true) {
double currentValue = atomic.get();
double nextValue = currentValue + delta;
if (atomic.compareAndSet(currentValue, nextValue))
return nextValue;
}
}
public final double incrementAndGet() {
return addAndGet(1);
}
public final void set(double newValue) {
atomic.set(newValue);
}
public final double get() {
return atomic.get();
}
public final double getAndSet(double newValue) {
return atomic.getAndSet(newValue);
}
public float floatValue() {
return (float) get();
}
#Override
public double doubleValue() {
return get();
}
public int intValue() {
return (int) get();
}
public long longValue() {
return (long) get();
}
public String toString() {
return Double.toString(get());
}
}
public class BankAccount {
private final AtomicDouble balance;
private String accountNumber;
public BankAccount(double balance, String accountNumber) {
this.balance = new AtomicDouble(balance);
this.accountNumber = accountNumber;
}
public void deposit(double number, String color) {
System.out.println(color + "deposit " + number + " current balance=" + balance.addAndGet(number));
}
public void withdraw(double number, String color) {
if (this.balance.get() - number >= 0) {
System.out.println(color + "Withdraw " + number + " current balance=" + balance.addAndGet(-number));
return;
}
System.out.println(color + "Not enough balance");
}
public static void main(String[] args) {
BankAccount bankAccount = new BankAccount(1000.0, "4234236");
ExecutorService threadsPool = Executors.newFixedThreadPool(2);
threadsPool.execute(new Runnable() {
#Override
public void run() {
bankAccount.deposit(300.0, ThreadColor.ANSI_YELLOW);
bankAccount.withdraw(50.0, ThreadColor.ANSI_YELLOW);
}
});
threadsPool.execute(new Runnable() {
#Override
public void run() {
bankAccount.deposit(203.75, ThreadColor.ANSI_BLUE);
bankAccount.withdraw(100.0, ThreadColor.ANSI_BLUE);
}
});
threadsPool.shutdown();
}
}
output: There is no output
I would suppose it is because of autoboxing. You can't have a reference to double, you have a reference to Double.
The operands get "reboxed" each time around the loop and therefore references are never identical. That is, the reference in currentValue is never the same as the reference in atomic.
Try using currentValue reference types.
public final double addAndGet(double delta) {
while (true) {
Double currentValue = atomic.get();
Double nextValue = currentValue + delta;
if (atomic.compareAndSet(currentValue, nextValue))
return nextValue;
}
}
(Fortunately, Double is an immutable type, otherwise this would have a race hazard)

I cannot figure out why my output is not displaying correctly from interface

So I am currently learning about interfaces within java and in this program I created 3 separate classes Building.class, Bicycle.class, and Car.class and they are unrelated but they all use the CarbonFootPrint Interface. in my processCarbonFootPrintData class I created an arrayList that holds the data from my objects then I loop through the array list and I get this weird output that does not show the result of my input data.
package CarbonFootPrintPackage;
import java.util.Scanner;
/**
*
* #author cjt1496
*/
public class Building implements CarbonFootPrintInterface {
private int numberOfFloors;
private int numberOfJanitors;
private boolean isBuildingOpenOrClosed;
double naturalGasConsumed;
Scanner input = new Scanner(System.in);
public double getNaturalGasConsumed() {
return naturalGasConsumed;
}
public void setNaturalGasConsumed(double naturalGasConsumed) {
this.naturalGasConsumed = naturalGasConsumed;
}
public int getNumberOfFloors() {
return numberOfFloors;
}
public void setNumberOfFloors(int numberOfFloors) {
this.numberOfFloors = numberOfFloors;
}
public int getNumberOfJanitors() {
return numberOfJanitors;
}
public void setNumberOfJanitors(int numberOfJanitors) {
this.numberOfJanitors = numberOfJanitors;
}
public boolean isIsBuildingOpenOrClosed() {
return isBuildingOpenOrClosed;
}
public void setIsBuildingOpenOrClosed(boolean isBuildingOpenOrClosed) {
this.isBuildingOpenOrClosed = isBuildingOpenOrClosed;
}
public Building(){
}
public Building(int numberOfFloors, int numberOfJanitors, boolean isBuildingOpenOrClosed, double naturalGasConsumed) {
this.numberOfFloors = numberOfFloors;
this.numberOfJanitors = numberOfJanitors;
this.isBuildingOpenOrClosed = isBuildingOpenOrClosed;
this.naturalGasConsumed = naturalGasConsumed;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for a Building ");
System.out.println("--------------------------------------------------------");
System.out.println("How many therms of natural gas has your building consumed?");
naturalGasConsumed = input.nextDouble();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this building is " +
(getNaturalGasConsumed() * 11.7) + "pounds of CO2 from natural gas use.\n");
}
}
START OF CAR.CLASS
public class Car implements CarbonFootPrintInterface {
private int numberOfSeats;
private int steeringWheel;
double emissionConversionFactor;
double distanceTraveled;
int numberOfTimesTraveled;
Scanner input = new Scanner(System.in);
public int getNumberOfSeats() {
return numberOfSeats;
}
public void setNumberOfSeats(int numberOfSeats) {
this.numberOfSeats = numberOfSeats;
}
public int getSteeringWheel() {
return steeringWheel;
}
public void setSteeringWheel(int steeringWheel) {
this.steeringWheel = steeringWheel;
}
public double getEmissionConversionFactor() {
return emissionConversionFactor;
}
public void setEmissionConversionFactor(double emissionConversionFactor) {
this.emissionConversionFactor = emissionConversionFactor;
}
public double getDistanceTraveled() {
return distanceTraveled;
}
public void setDistanceTraveled(double distanceTraveled) {
this.distanceTraveled = distanceTraveled;
}
public int getNumberOfTimesTraveled() {
return numberOfTimesTraveled;
}
public void setNumberOfTimesTraveled(int numberOfTimesTraveled) {
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public Car(){
}
public Car(int numberOfSeats, int steeringWheel, double emissionConversionFactor, double distanceTraveled, int numberOfTimesTraveled) {
this.numberOfSeats = numberOfSeats;
this.steeringWheel = steeringWheel;
this.emissionConversionFactor = emissionConversionFactor;
this.distanceTraveled = distanceTraveled;
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for a Car ");
System.out.println("--------------------------------------------------------");
System.out.println("Enter your emissionConversionFactor (Must be a decimal)");
emissionConversionFactor = input.nextDouble();
System.out.println("Enter your distance traveled in km (Must be a decimal)");
distanceTraveled = input.nextDouble();
System.out.println("Enter the number of times you traveled to your destination");
numberOfTimesTraveled = input.nextInt();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this bicycle is " +
getEmissionConversionFactor() * (getDistanceTraveled() * getNumberOfTimesTraveled()) +"Kg CO2e\n");
}
}
START OF BICYCLE.CLASS
import java.util.Scanner;
public class Bicycle implements CarbonFootPrintInterface {
private int handleBars;
private boolean KickStand;
double emissionConversionFactor;
double distanceTraveled;
int numberOfTimesTraveled;
Scanner input = new Scanner(System.in);
public int getHandleBars() {
return handleBars;
}
public void setHandleBars(int handleBars) {
this.handleBars = handleBars;
}
public boolean isKickStand() {
return KickStand;
}
public void setKickStand(boolean KickStand) {
this.KickStand = KickStand;
}
public double getEmissionConversionFactor() {
return emissionConversionFactor;
}
public void setEmissionConversionFactor(double emissionConversionFactor) {
this.emissionConversionFactor = emissionConversionFactor;
}
public double getDistanceTraveled() {
return distanceTraveled;
}
public void setDistanceTraveled(double distanceTraveled) {
this.distanceTraveled = distanceTraveled;
}
public int getNumberOfTimesTraveled() {
return numberOfTimesTraveled;
}
public void setNumberOfTimesTraveled(int numberOfTimesTraveled) {
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public Bicycle(){
}
public Bicycle(int handleBars, boolean KickStand, double emissionConversionFactor, double distanceTraveled, int numberOfTimesTraveled) {
this.handleBars = handleBars;
this.KickStand = KickStand;
this.emissionConversionFactor = emissionConversionFactor;
this.distanceTraveled = distanceTraveled;
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for Bicycle ");
System.out.println("--------------------------------------------------------");
System.out.println("Enter your emissionConversionFactor (Must be a decimal)");
emissionConversionFactor = input.nextDouble();
System.out.println("Enter your distance traveled in km (Must be a decimal)");
distanceTraveled = input.nextDouble();
System.out.println("Enter the number of times you traveled to your destination");
numberOfTimesTraveled = input.nextInt();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this bicycle is " +
getEmissionConversionFactor() * (getDistanceTraveled() * getNumberOfTimesTraveled()) +"Kg CO2e\n");
}
START Of PROCESS_CARBON_FOOTPRINT_DATA CLASS
public class ProcessCarbonFootPrintData {
public void createCarbonFootPrint(){
Building newBuilding = new Building();
Car newCar = new Car();
Bicycle newBicycle = new Bicycle();
newBuilding.calculateCarbonFootPrint();
newCar.calculateCarbonFootPrint();
newBicycle.calculateCarbonFootPrint();
ArrayList footPrint = new ArrayList();
footPrint.add(newBuilding);
footPrint.add(newCar);
footPrint.add(newBicycle);
for (Object footPrint1 : footPrint) {
System.out.println(footPrint1.toString());
}
}
}
This is the output I am getting:
CarbonFootPrintPackage.Building#42a57993
CarbonFootPrintPackage.Car#75b84c92
CarbonFootPrintPackage.Bicycle#6bc7c054
ArrayList footPrint = new ArrayList();
footPrint.add(newBuilding);
footPrint.add(newCar);
footPrint.add(newBicycle);
for (Object footPrint1 : footPrint) {
System.out.println(footPrint1.toString());
}
Your arraylist contains Objects, it doesn't know anything further of the type. When you do:
for ( Object footPrint1 : footPrint) {
}
You also declare the elements to be of type Object.
There are two things you need to do:
Be specific about the type. If you want to keep your List as is, with the different types, change your loop to:
for ( Object footPrint1 : footPrint) {
if ( footPrint1 instanceof Car )
System.out.println((Car)footPrint1);
else if ( footPrint1 instanceof Building )
System.out.println((Building)footPrint1);
else System.out.println((Bicycle)footPrint1);
}
This way, it'll know what type of data to print.
By just doing that, you'll still run into the same issue, because you haven't overridden your toString methods.
Add the following to your Car class:
#Override
public String toString() {
return "I am a car!!";
}
and you'll see that for the Car instance, that line is printed, instead of the memory address.
Override that method for all your classes, and alter the value returned by it the way you want it to be.

This is MobileServiceProvider Java Program Problem

I need help with how to get those private final values from the MobileServiceProvider Class to make it works to my MobileSericeProviderTest Class.
Description: Design a class that calculates a customer's monthly bill.It should store the letter of the package the customer has purchased (A, B, or C) and the number of miniutes that were used. it should have a method that returns the total charges. Demonstrate the class in a program that asks the user to select a package and enter the number of minutes used. The program should display the total charges.
package mobileserviceprovider;
public class MobileServiceProvider
{
private final double COST_A = 39.99;
private final double COST_B = 59.99;
private final double COST_C = 69.99;
private final int MIN_A = 450;
private final int MIN_B = 900;
private final double OVER_A = 0.45;
private final double OVER_B = 0.40;
String customer_Package;
double customer_TimeUse;
MobileServiceProvider() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public double getCostA()
{
return COST_A;
}
public int getMinA()
{
return MIN_A;
}
public String getPackage()
{
return customer_Package;
}
public double getHours()
{
return customer_TimeUse;
}
public void setPackage( String customer_Package )
{
this.customer_Package = customer_Package;
}
public void setHours( double customer_TimeUse )
{
this.customer_TimeUse = customer_TimeUse;
}
public MobileServiceProvider( String pack, double time )
{
customer_Package = pack;
customer_TimeUse = time;
{
}
}
}
}
package mobileserviceprovider;
import java.util.Scanner;
public class MobileServiceProviderTest
{
public static void main(String[] args)
{
String enter_Package = null;
double enter_Hours;
double min_A;
double bill;
Scanner keyboard = new Scanner(System.in);
System.out.print("What is your package type?");
keyboard.nextLine();
System.out.print("How many hours did you use for this package?");
enter_Hours = keyboard.nextDouble();
keyboard.nextLine();
MobileServiceProvider calMobileSP = new MobileServiceProvider();
calMobileSP.setPackage(enter_Package);
calMobileSP.setHours(enter_Hours);
calMobileSP.getMinA();
switch ( enter_Package)
{
case "A":
{
if (enter_Hours <= MIN_A)
bill = COST_A;
else
bill = COST_A + OVER_A * (enter_Hours - MIN_A)
}
}
}
}

How to make a collection of objects per each object

How to make for example list of Plane per each different airport?
I would like to create in this example the airport and when its this particular object(airport) , I would like to add a plane to collection of this airport.
How to make for example list of Plane per each diffrent airport?
I would like to create in this example the airport and when its this particual object(airport) i would like to add a plane to collection of this airport.
For example:
public class Airport {
private Plane plane;
Queue<Plane> queueOfPlanes = new ArrayDeque<Plane>();
public Airport(Plane plane) {
this.plane = plane;
queueOfPlanes.add(plane);
}
I am creating an airport, and when I have this specific airport I would like to gather the plane in the Queue for this one airport.
You start by having a different interface for your Airport.
Like:
private Plane plane; ...
public Airport(Plane plane) {
That is already wrong. An Airport doesn't need a specific single plane to be an airport.
Rather go:
class Airport {
private final List<Plane> currentPlanes = new ArrayList<>();
private final String name;
public Airport(String name) {
this.name = name;
}
public void addPlane(Plane plane) { currentPlanes.add(plane); }
public void removePlane(Plane plane) { currentPlanes.remove(plane); }
The idea here: an Airport has specific properties that don't change (like its name, location, ...). But the planes come and go. So your airport objects need a way to store which planes are currently associated to it.
There are many ways to do it but I think HashMaps are the best for your scenario, Let's see an example.
HashMap<String, ArrayList<Plane>> mAirPorts = new HashMap<String, ArrayList<Plane>>();
Now you need to create Object Plane
public class Plane
{
private double maxWeight;
private double emptyWeight;
private double loadWeight;
private double travelSpeed;
private double flyHours;
private double consumption;
private double maxFuel;
private double kerosinStorage;
public Plane( double maxWeight, double emptyWeight, double loadWeight,
double travelSpeed, double flyHours, double consumption,
double maxFuel, double kerosinStorage )
{
this.maxWeight = maxWeight;
this.emptyWeight = emptyWeight;
this.loadWeight = loadWeight;
this.travelSpeed = travelSpeed;
this.flyHours = flyHours;
this.consumption = consumption;
this.maxFuel = maxFuel;
this.kerosinStorage = kerosinStorage < this.maxFuel
? kerosinStorage
: this.maxFuel;
}
public double getMaxWeight()
{
return maxWeight;
}
public double getEmptyWeight()
{
return emptyWeight;
}
public double getLoadWeight()
{
return loadWeight;
}
public double getTravelSpeed()
{
return travelSpeed;
}
public double getFlyHours()
{
return flyHours;
}
public double getConsumption()
{
return consumption;
}
public double getMaxFuel()
{
return maxFuel;
}
public double getKerosinStorage()
{
return kerosinStorage;
}
public void setMaxWeight(double maxWeight)
{
this.maxWeight = maxWeight;
}
public void setEmptyWeight(double emptyWeight)
{
this.emptyWeight = emptyWeight;
}
public void setLoadWeight(double loadWeight)
{
this.loadWeight = loadWeight;
}
public void setTravelSpeed(double travelSpeed)
{
this.travelSpeed = travelSpeed;
}
public void setFlyHours(double flyHours)
{
this.flyHours = flyHours;
}
public void setConsumption(double consumption)
{
this.consumption = consumption;
}
public void setMaxFuel(double maxFuel)
{
this.maxFuel = maxFuel;
}
public void setKerosinStorage(double kerosinStorage)
{
this.kerosinStorage = this.kerosinStorage + kerosinStorage > maxFuel
? maxFuel : this.kerosinStorage + kerosinStorage;
}
/*
Returns the total weight of the plane. Which is: emptyWeight +
weight of load + weight of kerosin.
Expect 1 liter Kerosin as 0.8 kg.
*/
public double getTotalWeight ()
{
return emptyWeight + loadWeight
+ (kerosinStorage * 0.8);
}
/*
How far can the plane fly with the current kerosin storage?
*/
public double getMaxReach ()
{
return (kerosinStorage / consumption) * travelSpeed;
}
/*
Prevent flying further then possible (with the current kerosin) !
*/
public boolean fly (double km)
{
if (km <= 0 || getMaxReach() < km || getTotalWeight() > maxWeight)
{
return false;
}
flyHours += (km / travelSpeed);
kerosinStorage -= (km / travelSpeed) * consumption;
return true;
}
/*
! The parameter 'liter' can be a negative number.
Doesn't have to be overfilled.
Prevent a negative number as value of the 'kerosinStorage' property !
*/
public void fillUp (double liter)
{
if ((kerosinStorage + liter) > maxFuel)
{
kerosinStorage = maxFuel;
}
else if ((kerosinStorage + liter) < 0)
{
kerosinStorage = 0;
}
else
{
kerosinStorage += liter;
}
}
/*
Prevent illogical value-assignments !
*/
public boolean load (double kg)
{
if ((loadWeight + emptyWeight + kg) > maxWeight)
{
return false;
}
else if ((emptyWeight + kg) < 0)
{
loadWeight = 0;
return true;
}
else
{
loadWeight += kg;
return true;
}
}
// Display flying hours, kerosin storage & total weight on t. terminal.
public void info ()
{
System.out.println("Flying hours: " + flyHours + ", Kerosin: "
+ kerosinStorage + ", Weight: " + getTotalWeight());
}
}
Now simply add objects to your HashMap like:
mAirPorts.put("airport_key", ArrayListContainingPlanes);
You can now get planes by your airport key like:
ArrayList<Plane> mPlanes = mAirPorts.get("airport_key");
if (mPlanes != null) {
...
} else {
//No such airport
}

Java custom exception class

I am having a rather trivial problem creating my own exception class. I have extending it and am trying to recieve a double in the constructor but I keep getting errors.
Error inside of bankaccount #withdraw "incompatible types: InsufficientFundsException cannot be converted to throwable"
Exception class:
public class InsufficientFundsException extends RuntimeException {
private double shortFall;
public InsufficientFundsException(double a) {
super("Insufficient funds");
shortFall = a;
}
public double getAmount() { return shortFall; }
}
Bank Account class:
public class BankAccount {
private int accountNumber;
private double balance;
// Class constructor
public BankAccount(int account) {
accountNumber = account;
balance = 0.0;
}
public int getAccountNumber() {
return accountNumber;
}
public double getBalance()
{
return balance;
}
public void deposit(double b) {
balance += b;
}
public void withdraw(double w) throws InsufficientFundsException {
double difference;
if(w > balance) {
difference = w - balance;
} else {
balance -= w;
}
}
I would like to withdraw money unless the withdraw is greater than the current balance. In which case I want to throw an exception. I also tried to throw and exception inside of the if but I get:
constructor InsufficientFundsException in class InsufficientFundsException cannot be applied to gived types;
required: no arguments
found: double
reason: actual and formal argument lists differ in length
public void withdraw(double w) {
double difference;
if(w > balance) {
difference = w - balance;
Exception ex = new InsufficientFundsException(difference);
} else {
balance -= w;
}
}
I only have the one constructor though. Any advice or help is appreciated.
Have you tried...
throw new InsufficientFundsException(difference);
in place of
Exception ex = new InsufficientFundsException(difference);
That's generally how exceptions are thrown.
Updated code snippet...
public void withdraw(double w) throws InsufficientFundsException {
double difference;
if(w > balance) {
difference = w - balance;
throw new InsufficientFundsException(difference);
} else {
balance -= w;
}
}
Ran with...
public static void main(String[] args){
BankAccount account = new BankAccount(1);
account.withdraw(5.0);
}
Got....
Exception in thread "main" com.misc.help.InsufficientFundsException: Insufficient funds
at com.misc.help.BankAccount.withdraw(BankAccount.java:32)
at com.misc.help.BankAccount.main(BankAccount.java:40)

Categories