Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import static java.lang.System.*;
- import java.util.ArrayList;
- import java.io.*;
- import java.util.*;
- public class Java3002{
- public static void main (String[] args){
- new Purse();
- }}
- class Purse
- {
- private List<Coin> money = new ArrayList<Coin> ();
- // private double total = 0;
- Purse()
- {
- populate();
- outputAll();
- countCoins();
- outputTotal();
- removePennies();
- countCoins();
- outputTotal();
- }
- void populate()
- {
- money = new ArrayList<Coin>();
- try{
- Scanner fileScan = new Scanner(new File("Java3002.dat"));
- while(fileScan.hasNext())
- {
- Double cost = Double.valueOf( fileScan.next() );
- String cn = fileScan.next();
- money.add( new Coin( cost, cn) );
- }
- }catch(Exception e){}
- }
- void outputAll()
- {
- out.println();
- out.println( money );
- out.println();
- }
- void removePennies()
- {
- for(int x = money.size()-1; x > -1; x--)
- {
- if(money.get(x).getName().equals("penny"))
- {
- money.remove(x);
- }
- }
- out.println("NOW REMOVING PENNIES!\n");
- }
- void outputTotal()
- {
- Double total = 0.0;
- for(Coin t: money)
- {
- if(t.getName().equals("penny"))
- {
- total = total + 0.01;
- }
- else
- if(t.getName().equals("dime"))
- {
- total = total + 0.10;
- }
- else
- if(t.getName().equals("nickel"))
- {
- total = total + 0.05;
- }
- else
- total = total + 0.25;
- } // use a for each loop to total the coins
- out.println("The total of your coins: " + String.format("$%.2f", total) );
- out.println();
- }
- public void countCoins()
- {
- int pennies = 0;
- int dimes = 0;
- int nickels = 0;
- int quarters = 0;
- for(Coin c: money)
- {
- if( c.getName().equals("penny") )
- {
- pennies++;
- }
- else
- if( c.getName().equals("dime") )
- {
- dimes++;
- }
- else
- if( c.getName().equals("nickel") )
- {
- nickels++;
- }
- else
- {
- quarters++;
- }
- } // use a for each loop to count the coins
- out.println(pennies + " pennies");
- out.println(nickels + " nickels");
- out.println(dimes + " dimes");
- out.println(quarters + " quarters");
- }
- }
- class Coin
- {
- private double value;
- private String name;
- public Coin( double v, String n)
- {
- value = v;
- name = n;
- }
- public Double getValue()
- {
- return value;
- }
- public String getName()
- {
- return name;
- }
- public String toString()
- {
- return "<" + value + "," + name + ">";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement