Java Tutorial: Get kinds of Coins from a money value - TheWiz - 03-01-2011
This is a sample of how to use basic Java classes to return the amount of quarters, dimes, nickels, and pennies from any amount of money given.
Download source code: http://dl.dropbox.com/u/1525839/Java/TwoClasses2.zip
Coins.java (main class)
Code: import java.util.Scanner;
import java.text.DecimalFormat;
public class Coins
{
DecimalFormat twoDigits = new DecimalFormat("####");
public static void main(String[] args)
{
menu();
}
public static void menu()
{
Scanner keyboard = new Scanner(System.in);
double cents;
System.out.println("\t1. Press One to calculate cents.");
System.out.println("\t2. Exit program.");
int choice = keyboard.nextInt();
switch(choice)
{
case 1:
{
System.out.println("\n\n\nEnter amount of cents.");
cents = keyboard.nextDouble();
Calc instance01 = new Calc(cents);
break;
}
case 2:
{
System.exit(0);
break;
}
default:
{
menu();
break;
}
}
}
public void recieveInfoCoinage(double q, double d, double n, double p)
{
System.out.println("Quarters: " + twoDigits.format(q));
System.out.println("Dimes: " + twoDigits.format(d));
System.out.println("Nickels: " + twoDigits.format(n));
System.out.println("Pennies: " + twoDigits.format(p));
menu();
}
}import java.util.Scanner;
import java.text.DecimalFormat;
public class Coins
{
DecimalFormat twoDigits = new DecimalFormat("####");
public static void main(String[] args)
{
menu();
}
public static void menu()
{
Scanner keyboard = new Scanner(System.in);
double cents;
System.out.println("\t1. Press One to calculate cents.");
System.out.println("\t2. Exit program.");
int choice = keyboard.nextInt();
switch(choice)
{
case 1:
{
System.out.println("\n\n\nEnter amount of cents.");
cents = keyboard.nextDouble();
Calc instance01 = new Calc(cents);
break;
}
case 2:
{
System.exit(0);
break;
}
default:
{
menu();
break;
}
}
}
public void recieveInfoCoinage(double q, double d, double n, double p)
{
System.out.println("Quarters: " + twoDigits.format(q));
System.out.println("Dimes: " + twoDigits.format(d));
System.out.println("Nickels: " + twoDigits.format(n));
System.out.println("Pennies: " + twoDigits.format(p));
menu();
}
}
Calc method (private subclass)
Code: public class Calc extends Coins
{
private double coinage, quarters, dimes, nickels, pennies;
Calc(double cents)
{
coinage = cents;
calculateCoinage();
}
private void calculateCoinage()
{
if(coinage > 24)
{
quarters = Math.floor(coinage / 25);
coinage = coinage - (quarters * 25);
}
if(coinage > 9)
{
dimes = Math.floor(coinage / 10);
coinage = coinage - (dimes * 10);
}
if(coinage > 4 )
{
nickels = Math.floor(coinage /5 );
coinage = coinage - (nickels * 5);
}
pennies = coinage;
Coins Coin01 = new Coins();
Coin01.recieveInfoCoinage(quarters, dimes, nickels, pennies);
}
}
|