working on this code since this morning all day, it a demo from a book online for some reason getting null pointer exception at main() and also logic seems bit not working, can someone spend bit of his time gosh cant find the problem there thanks for help people
class Currency {
private int amount;
public Currency(int a) {
this.amount = a;
}
public int getAmount() {
return amount;
}
}
interface DispenseChain {
public void setNextChain(DispenseChain nextChain);
public void dispense(Currency cur);
}
class Dollar50Dispenser implements DispenseChain {
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain = nextChain;
}
@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 50) {
int num = cur.getAmount() / 50;
int remainder = cur.getAmount() % 50;
System.out.println("Dispensing " + num + " 50$ note");
if (remainder != 0) {
chain.dispense(new Currency(remainder));
} else {
chain.dispense(cur);
}
}
}
}
class Dollar20Dispenser implements DispenseChain {
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain = nextChain;
}
@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 20) {
int num = cur.getAmount() / 20;
int remainder = cur.getAmount() % 20;
System.out.println("Dispensing " + num + " 20$ note");
if (remainder != 0) {
chain.dispense(new Currency(remainder));
} else {
chain.dispense(cur);
}
}
}
}
class Dollar10Dispenser implements DispenseChain {
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain = nextChain;
}
@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 10) {
int num = cur.getAmount() / 10;
int remainder = cur.getAmount() % 10;
System.out.println("Dispensing " + num + " 10$ note");
if (remainder != 0) {
chain.dispense(new Currency(remainder));
} else {
chain.dispense(cur);
}
}
}
}
class DemoChainResponsibilityPattern1 {
private DispenseChain c1;
public DemoChainResponsibilityPattern1() {
c1 = new Dollar50Dispenser();
DispenseChain c2 = new Dollar20Dispenser();
DispenseChain c3 = new Dollar10Dispenser();
// set the the chain of responsibility
c1.setNextChain(c2);
c2.setNextChain(c3);
}
public static void main(String[] args) {
DemoChainResponsibilityPattern1 dispenser = new DemoChainResponsibilityPattern1();
while (true) {
int amount = 0;
System.out.println("Enter amount to dispense: ");
Scanner input = new Scanner(System.in);
amount = input.nextInt();
if (amount % 10 != 0) {
System.out.println("amount must be in multiple of 10s");
return;
}
// process the request
dispenser.c1.dispense(new Currency(amount));
}
}
}