Have a go!!!
This should help others like me who are new to programming and would like different examples of ways a program can be constructed and different styles!
Brief: Construct an application in Java to work out the minimum number of coins to be delivered in change for an amount of money between 1p and 500p.
The coins that are available to be given in change are: The £2 coin, the £1 coin, the 50p coin, the 20p coin, the 10p coin, the 5p coin, the 2p coin and finally the 1p coin.
For example, if 342p was to be given in change the minimum number of individual coins used would be 5 as follows: 200p, 100p, 20p, 20p, 2p.
The output from the program to be: Amount Coins 342p 5 coins 200p 100p 2*20p 2p Note if only one coin then should print "1 coin"
Example Input Data:
498
10
0
Example Output (finished program should print out):
Amount Coins
498p 8 coins 2*200p 50p 2*20p 5p 2p 1p
10p 1coin10p
private static int iAmount = 427; //BIO.getInt(); Amount assigned
public static void main(String[] args)
{
int amount = 427; //BIO.getInt(); random number will be assigned. 1 - 500
int i = 0; //Amount of coins used
//Use these variables to print out what coins were used
int twoHundred = 0;
int oneHundred = 0;
int fifty = 0;
int twenty = 0;
int ten = 0;
int five = 0;
int two = 0;
int one = 0;
//
if (amount >500)
{
System.out.print("Invalid Aamount " + iAmount + "p");
System.exit(0);
} else {
System.out.println("Amount Coins");
while (amount >= 200)
{
amount -= (200);
i++;
twoHundred++;
}
while (amount >= 100)
{
amount -= (100);
i++;
oneHundred++;
}
while (amount >= 50)
{
amount -= (50);
i++;
fifty++;
}
while (amount >= 20)
{
amount -= (20);
i++;
twenty++;
}
while (amount >= 10)
{
amount -= (10);
i++;
ten++;
}
while (amount >= 5)
{
amount -= (5);
i++;
five++;
}
while (amount >= 2)
{
amount -= (2);
i++;
two++;
}
while (amount >= 1)
{
amount -= (1);
i++;
one++;
}
System.out.printf((iAmount)+"p" + " " + (i) + " coins");
}
}
}
Aucun commentaire:
Enregistrer un commentaire