-1

I want to create a program where you're able to add and remove coins to a wallet, as well as show the total amount of money in the wallet. All through OOP. I've created a while loop where there are multiple options the user can choose from. Which is add coins, display num of coins, and remove coins from wallet.

What I am struggling with is how to keep track of these coins, for example: if I add a dime 2 times and a quarter 3 times, I want the program to count those times + the values and add it into the wallet, calculating the total.

Main class

import java.text.DecimalFormat;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
     Coin myCoin = new Coin();
    Wallet myWallet = new Wallet();

  while(true) {

    Scanner input = new Scanner(System.in);

    // Options

    System.out.println("Select an option: ");
    System.out.println("1. Enter a coin to add");
    System.out.println("2. Display number of coins");
    System.out.println("3. Remove Coins from Wallet");
    System.out.println("4. Exit Program");
    int choice = input.nextInt();

    // If statements for 1

    if (choice == 1) {
      System.out.println("Enter the coin name: ");
      String coin = input.next();
      if (coin.equals("Dime")) {
        myCoin.setName("Dime");
        System.out.println(myCoin.getName()); }
        
       else if (coin.equals("Quarter")) {
        myCoin.setName("Quarter");
        System.out.println(myCoin.getName());
      }
      else if (coin.equals("Nickel")) {
        myCoin.setName("Nickel");
        System.out.println(myCoin.getName());
      }
      else if (coin.equals("Loonie")) {
        myCoin.setName("Loonie");
        System.out.println(myCoin.getName());
      }

      else if (coin.equals("Toonie")) {
        myCoin.setName("Toonie");
        System.out.println(myCoin.getName());
      }
    }

    

    // If statements for 2

  if (choice == 2) {
    System.out.println("Coins in your wallet: ");
    System.out.println("Toonies: " + myWallet.getToonies());
    System.out.println("Loonies: " + myWallet.getLoonie());
    System.out.println("Quarters: " + myWallet.getQuarter());
    System.out.println("Dimes: " + myWallet.getDimes());
    System.out.println("Nickels: " + myWallet.getNickel());

    System.out.println("Total Money: $" + new DecimalFormat("#0.00").format(myWallet.totalCoins()));
  }

    // If statements for 3
    
    if (choice == 3) {
      System.out.println("Enter coin to remove: ");
      String removeCoin = input.next();
      System.out.println("Enter the amount of coins: ");
      String amountRemoved = input.next();
    }
    
    // If statements for 4
    if (choice == 4) {
     
      System.exit(0);
    }
  }
  }
}

Coin Class

import java.text.DecimalFormat;
class Coin {

private String name;
private double value;



  
  public void setName(String name) { 
  this.name = name;

    //dime 
    if (name.equals("Dime")) {
     this.value = 0.1;
    }
    //quarter
    if (name.equals("Quarter")) {
     this.value = 0.25;
    }
    //nickel
    if (name.equals("Nickel")) {
      this.value = 0.05;
    }
    //loonie
    if (name.equals("Loonie")) {
      this.value = 1.0;
    }
    //toonie
    if (name.equals("Toonie")) {
      this.value = 2.0;
    }
    
  }
    

  public String getName() {
  return "You added a " + this.name + ". Value is $" + new DecimalFormat("#0.00").format(this.value);
  }

}

Wallet Class

import java.util.ArrayList;

class Wallet {

  private int toonies;
  private int loonie;
  private int quarter;
  private int dimes;
  private int nickel;

// array list

  private ArrayList<String> coins = new ArrayList<>();

  
  //setters

  public void setToonies(int toonies) {
    this.toonies = toonies;
  }
  public void setLoonie(int loonie) {
    this.loonie = loonie;
  }
  public void setQuarter(int quarter) {
    this.quarter = quarter;
  }
  public void setDimes(int dimes) {
    this.dimes = dimes;
  }
  public void setNickel(int nickel) {
    this.nickel = nickel;
  }

  //getters

  public int getToonies() {
    return toonies;
  }
  public int getLoonie() {
    return loonie;
  }
  public int getQuarter() {
    return quarter;
  }
  public int getDimes() {
    return dimes;
  }
  public int getNickel() {
    return nickel;
  }

  // total number of coins

  public int totalCoins() {
    return toonies + loonie + quarter + dimes + nickel;
  }

  
  
}

I've tried using increments to count the different coins in the Coin class but they would not work out for me and I'm trying to use an ArrayList because I'm pretty sure I need that to store the coins, but I am not well-versed in this kind of code so I am confused on how to go about this.

Also, I am not sure if the explanation of my problem is coherent or not, so feel free to ask for clarification on anything I have said

2
  • from what i understand, your coins array is not needed...as long as you keep count of the coins the array is useless...it be useful eg. to know in which order you put the coins, but that doesnt seem to be a requirement Commented Mar 4 at 5:03
  • Hint(s): you could/should use an enum for coin types (enum Type { DIME, QUARTER, NICKEL, ...} instead of Strings; if not possible/allowed/wanted, at least use constants for that (e.g. public static final String DIME = "Dime"; public static final String QUARTER = "Quarter"; ...`), so all parts are using the same constant
    – user85421
    Commented Mar 4 at 7:43

2 Answers 2

0

First of all, you have a Coin class and you are creating a object for it but you are not adding it to the wallet at all if user chooses option 1. To add Coin to Wallet. Wallet class must have one constructor with Coin as parameter. I have done some modifications to your code

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {
    
  public static void main(String[] args) {
      
      Wallet wallet = new Wallet();

      while(true) {
    
        Scanner input = new Scanner(System.in);
    
        // Options
    
        System.out.println("Select an option: ");
        System.out.println("1. Enter a coin to add");
        System.out.println("2. Display number of coins");
        System.out.println("3. Remove Coins from Wallet");
        System.out.println("4. Exit Program");
        int choice = input.nextInt();
    
        // If statements for 1
    
        if (choice == 1) {
          System.out.println("Enter the coin name: ");
          String coinName = input.next().trim();
          Coin coin = null;
          if(coinName.equals("Dime") || coinName.equals("Nickel") || coinName.equals("Loonie") || coinName.equals("Toonie") || coinName.equals("Quarter")) {
              coin = new Coin(coinName);
          }
          if(coin != null) {
              wallet.addCoin(coin);
              System.out.println("Coin added : " + coin.getName() + " " + coin.getValue());
              System.out.println("Wallet total amount : " + wallet.gettotalAmount());
          }
        }
    
        if (choice == 2) {
          System.out.println("Coins in your wallet: ");
          System.out.println("Toonies: " + wallet.getToonies());
          System.out.println("Loonies: " + wallet.getLoonies());
          System.out.println("Quarters: " + wallet.getQuarters());
          System.out.println("Dimes: " + wallet.getDimes());
          System.out.println("Nickels: " + wallet.getNickels());
    
          System.out.println("Total Money: $" + new DecimalFormat("#0.00").format(wallet.gettotalAmount()));
        }
    
        // If statements for 3
        
        if (choice == 3) {
          System.out.println("Enter coin to remove: ");
          String removeCoin = input.next();
          System.out.println("Enter the amount of coins: ");
          int removeAmount = input.nextInt();
          double amountRemoved = wallet.removeCoins(removeCoin, removeAmount);
          if(amountRemoved == 0.0) {
              System.out.println("You do not have enough coins");
              System.out.println("Wallet total amount : " + wallet.gettotalAmount());
          }
          else {
              System.out.println("Amount removed : $ " + amountRemoved);
          }
        }
        
        // If statements for 4
        if (choice == 4) {
          System.exit(0);
        }
     }
  }
}

class Coin {

private String name;
private double value;

  Coin(String name) { 
      
  this.name = name;

    if (name.equals("Dime")) {
     this.value = 0.1;
    }
    
    if (name.equals("Quarter")) {
     this.value = 0.25;
    }
    
    if (name.equals("Nickel")) {
      this.value = 0.05;
    }
    
    if (name.equals("Loonie")) {
      this.value = 1.0;
    }
    
    if (name.equals("Toonie")) {
      this.value = 2.0;
    }
    
  }
    

  public String getName() {
      return name;
  }
  
  public double getValue() {
      return value;
  }

}


class Wallet {

  private int toonies;
  private int loonies;
  private int quarters;
  private int dimes;
  private int nickels;
  
  private double totalAmount;
  Wallet() {
      toonies = 0;
      loonies = 0;
      quarters = 0;
      dimes = 0;
      nickels = 0;
      totalAmount = 0;
  }
  
  public void addCoin(Coin coin) {
      String name = coin.getName();
      switch(name) {
      case "Dime":
          dimes++;
          totalAmount+=coin.getValue();
          break;
      case "Quarter":
          quarters++;
          totalAmount+=coin.getValue();
          break;
      case "Nickel":
          nickels++;
          totalAmount+=coin.getValue();
          break;
      case "Loonie":
          loonies++;
          totalAmount+=coin.getValue();
          break;
      case "Toonie":
          toonies++;
          totalAmount+=coin.getValue();
          break;
      }
            
  }

  public int getToonies() {
    return toonies;
  }
  public int getLoonies() {
    return loonies;
  }
  public int getQuarters() {
    return quarters;
  }
  public int getDimes() {
    return dimes;
  }
  public int getNickels() {
    return nickels;
  }

  public int gettotalCoins() {
    return toonies + loonies + quarters + dimes + nickels;
  }
  
  public double gettotalAmount() {
     return totalAmount;
  }
  
  public double removeCoins(String name,int amount) {
      int currentAmount = 0;
      switch(name) {
          case "Dime":
              if(dimes - amount >= 0) {
                  dimes-=amount;
                  totalAmount-=amount*0.1;
                  return amount*0.1;
              }
              break;
          case "Quarter":
              if(quarters - amount >= 0) {
                  quarters-=amount;
                  totalAmount-=amount*0.25;
                  return amount*0.25;
              }
              break;
          case "Nickel":
              if(nickels - amount >= 0) {
                  nickels-=amount;
                  totalAmount-=amount*0.05;
                  return amount*0.05;
              }
              break;
          case "Loonie":
              if(loonies - amount >= 0) {
                  loonies-=amount;
                  totalAmount-=amount*1.0;
                  return amount*1.0;
              }
              break;
          case "Toonie":
              if(toonies - amount >= 0) {
                  toonies-=amount;
                  totalAmount-=amount*2.0;
                  return amount*2.0;
              }
              break;
          default:
              break;
      }
      return 0.0;
  }
  
}

Everything is pretty much self explanatory but to give you some overall idea. While getting input to add coin from user, We create a coin object with the provided name if it matches one of our valid types i.e Dime, Nickel, etc. The constructor in Coin class takes care of assigning the value to it. Then we add this object to the wallet object. Now the Wallet class has a constructor that takes Coin. This constructor adds the value of coin to total amount and also increases the number of coins. While removing, we provide the name of coin and amount, if its less than what we have in the wallet, it returns 0.0 . Otherwise, we will reduce the amount from the total amount and return the amount removed.

Note : This is not be the best way of creating coins and wallets, I have just made your code into a working one. You could find a way to improve the code yourself by looking how it works

Another way how this could be better implemented is by creating a Coin class first and creating the other types of coins such as Nickel, Dime, etc.., as a subclass of it. This will provide you some extra flexibility. For example,

class Coin {
   double value;
}
class Nickel extends Coin{
   Nickel() {
       this.value = 0.05;
   }
}
0

Here is my solution. Probably uses things that you have not yet learned. I have added links to the things that I believe you have not yet learned.

Also note, in the below code, that I added handling of invalid user input, for example entering a non-existent [menu] choice or not entering a number. Many beginner programmers assume that the user input will always be valid. You will learn, very quickly, that this is not always true.

Notes after the code.

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class Main {

    private static void addCoins(Scanner input, Wallet myWallet) {
        updateCoins(input, myWallet, true);
    }

    private static void displayCoins(Wallet myWallet) {
        myWallet.display();
    }

    private static void removeCoins(Scanner input, Wallet myWallet) {
        updateCoins(input, myWallet, false);
    }

    private static void updateCoins(Scanner input, Wallet myWallet, boolean adding) {
        String operation = adding ? "Add" : "Remov";
        System.out.println(operation + "ing coins...");
        Coin[] values = Coin.values();
        while (true) {
            int index = 0;
            for (Coin coin : values) {
                System.out.printf("%2d. %s%n", ++index, coin);
            }
            System.out.printf("Which coin? [1-%d] (0 to quit): ", index);
            try {
                int choice = input.nextInt();
                if (choice == 0) {
                    break;
                }
                if (choice > 0  &&  choice <= index) {
                    choice--;
                    while (true) {
                        int count = myWallet.getQuantity(values[choice]);
                        String plural = count == 1 ? "" : "s";
                        System.out.printf("You have %d %s%s.%n", count, values[choice], plural);
                        System.out.printf("How many %ss (0 to quit): ", values[choice]);
                        int quantity = input.nextInt();
                        if (quantity == 0) {
                            break;
                        }
                        if (quantity > 0) {
                            if (adding) {
                                myWallet.addCoin(values[choice], quantity);
                            }
                            else {
                                if (!myWallet.removeCoin(values[choice], quantity)) {
                                    continue;
                                }
                            }
                            break;
                        }
                        else {
                            System.out.println("Enter a number greater than zero.");
                            continue;
                        }
                    }
                    break;
                }
                else {
                    System.out.println("Invalid choice.");
                    continue;
                }
            }
            catch (InputMismatchException x) {
                input.nextLine();
                System.out.println("Enter a number.");
            }
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Wallet myWallet = new Wallet();
        while (true) {
            System.out.println("Select an option: ");
            System.out.println("1. Enter a coin to add");
            System.out.println("2. Display number of coins");
            System.out.println("3. Remove Coins from Wallet");
            System.out.println("4. Exit Program");
            try {
                int choice = input.nextInt();
                switch (choice) {
                    case 1:
                        addCoins(input, myWallet);
                        break;
                    case 2:
                        displayCoins(myWallet);
                        break;
                    case 3:
                        removeCoins(input, myWallet);
                        break;
                    case 4:
                        System.out.println("Exiting.");
                        System.exit(0);
                    default:
                        System.out.println("Invalid choice.");
                }
            }
            catch (InputMismatchException x) {
                input.nextLine();
                System.out.println("Enter a number.");
            }
        }
    }
}

enum Coin {
    NICKEL(new BigDecimal(0.05), "Nickel"),
    DIME(new BigDecimal(0.1), "Dime"),
    QUARTER(new BigDecimal(0.25), "Quarter"),
    LOONIE(new BigDecimal(1), "Loonie"),
    TOONIE(new BigDecimal(2), "Toonie");

    private BigDecimal  value;
    private String  name;

    private Coin(BigDecimal value, String name) {
        this.value = value;
        this.name = name;
    }
    
    public BigDecimal getVal() {
        return value;
    }

    public String toString() {
        return name;
    }
}

class Wallet {
    private Map<Coin, Integer>  quantities;

    public Wallet() {
        quantities = new HashMap<>();
        quantities.put(Coin.DIME, 0);
        quantities.put(Coin.NICKEL, 0);
        quantities.put(Coin.QUARTER, 0);
        quantities.put(Coin.LOONIE, 0);
        quantities.put(Coin.TOONIE, 0);
    }

    public void addCoin(Coin coin, int quantity) {
        Integer current = quantities.get(coin);
        quantities.put(coin, current + quantity);
    }

    public boolean removeCoin(Coin coin, int quantity) {
        boolean result = false;
        Integer current = quantities.get(coin);
        int newQuantity = current - quantity;
        if (newQuantity < 0) {
            String plural = current == 1 ? "" : "s";
            System.out.printf("You only have %d %s%s. You cannot remove %d.%n",
                              current,
                              coin,
                              plural,
                              quantity);
        }
        else {
            quantities.put(coin, newQuantity);
            result = true;
        }
        return result;
    }

    public void display() {
        System.out.println("Wallet currently contains following coins:");
        Set<Coin> coins = quantities.keySet();
        BigDecimal total = BigDecimal.valueOf(0.0);
        for (Coin coin : coins) {
            int number = quantities.get(coin);
            total = total.add(coin.getVal().multiply(new BigDecimal(number)));
            System.out.printf("%-7s: %d%n", coin, quantities.get(coin));
        }
        total = total.setScale(2, RoundingMode.HALF_UP);
        System.out.println("Total: " + total);
    }

    public int getQuantity(Coin coin) {
        return quantities.get(coin);
    }
}
  • You don't need to create a new Scanner each time you want to get input from the user. Create the Scanner once, before the while loop.
  • Since [variable] choice is an int, you can use a switch statement – rather than a series of if-else statements.
  • For doing calculations involving money, it is better to use class java.math.BigDecimal rather than double. Refer to this SO question: Retain precision with double in Java.
  • For ensuring displaying BigDecimal with exactly two places after the decimal point, refer to this SO question: How to display a number with always 2 decimal points using BigDecimal?
  • I replaced your Coin class with an enum.
  • Wallet class stores quantities of coins in a Map where the [map] key is a Coin and the [map] value is the number of that Coin in the Wallet.
  • Method nextInt (of class java.util.Scanner) throws InputMismatchException when an int is not entered. Hence the try-catch blocks that wrap calls to method nextInt. Also note that after method nextInt throws InputMismatchException, you need to call method nextLine before calling method nextInt again.

Output from a sample run of the above code:

Select an option: 
1. Enter a coin to add
2. Display number of coins
3. Remove Coins from Wallet
4. Exit Program
1
Adding coins...
 1. Nickel
 2. Dime
 3. Quarter
 4. Loonie
 5. Toonie
Which coin? [1-5] (0 to quit): 3
You have 0 Quarters.
How many Quarters (0 to quit): 3
Select an option: 
1. Enter a coin to add
2. Display number of coins
3. Remove Coins from Wallet
4. Exit Program
2
Wallet currently contains following coins:
Quarter: 3
Toonie : 0
Dime   : 0
Loonie : 0
Nickel : 0
Total: 0.75
Select an option: 
1. Enter a coin to add
2. Display number of coins
3. Remove Coins from Wallet
4. Exit Program
3
Removing coins...
 1. Nickel
 2. Dime
 3. Quarter
 4. Loonie
 5. Toonie
Which coin? [1-5] (0 to quit): 3
You have 3 Quarters.
How many Quarters (0 to quit): 4
You only have 3 Quarters. You cannot remove 4.
You have 3 Quarters.
How many Quarters (0 to quit): 1
Select an option: 
1. Enter a coin to add
2. Display number of coins
3. Remove Coins from Wallet
4. Exit Program
2
Wallet currently contains following coins:
Quarter: 2
Toonie : 0
Dime   : 0
Loonie : 0
Nickel : 0
Total: 0.50
Select an option: 
1. Enter a coin to add
2. Display number of coins
3. Remove Coins from Wallet
4. Exit Program
4
Exiting.

Not the answer you're looking for? Browse other questions tagged or ask your own question.