I was tasked with writing a method which would take in an int
(for amount in coins) and then convert the coins, accordingly, by counting how many quarters, dimes, nickels, and pennies were located in the amount. Afterwards, it would return a String
which stated each count of individual coin.
public class Coins {
private static final int QUARTER_VALUE = 25;
private static final int DIME_VALUE = 10;
private static final int NICKEL_VALUE = 5;
private static final int PENNY_VALUE = 1;
public static String convert(int amount) {
int currentAmount = amount;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
String quarterUnit = new String();
String dimeUnit = new String();
String nickelUnit = new String();
String pennyUnit = new String();
if (amount != 0) {
quarters = amount / QUARTER_VALUE;
currentAmount =
amount - (quarters * QUARTER_VALUE);
dimes = currentAmount / DIME_VALUE;
currentAmount =
amount - (quarters * QUARTER_VALUE) - (dimes * DIME_VALUE);
nickels = currentAmount / NICKEL_VALUE;
currentAmount =
amount - (quarters * QUARTER_VALUE)
- (dimes * DIME_VALUE) - (nickels * NICKEL_VALUE);
pennies = currentAmount / PENNY_VALUE;
}
if (quarters == 1) {
quarterUnit = " quarter";
}
else if (quarters > 1 || quarters == 0){
quarterUnit = " quarters";
}
if (dimes == 1) {
dimeUnit = " dime";
}
else if (dimes > 1 || dimes == 0) {
dimeUnit = " dimes";
}
if (nickels == 1) {
nickelUnit = " nickel";
}
else if (nickels > 1 || nickels == 0) {
nickelUnit = " nickels";
}
if (pennies == 1) {
pennyUnit = " penny";
}
else if (pennies > 1 || pennies == 0) {
pennyUnit = " pennies";
}
StringBuilder conversion = new StringBuilder();
return conversion.append(quarters)
.append(quarterUnit)
.append("\n")
.append(dimes)
.append(dimeUnit)
.append("\n")
.append(nickels)
.append(nickelUnit)
.append("\n")
.append(pennies)
.append(pennyUnit)
.append("\n")
.toString();
}
public static void main(String[] args) {
String conversionString = convert(89);
System.out.println(
new StringBuilder().append("Converted amount equates to: ")
.append("\n"));
System.out.println(conversionString);
}
}
Here's the output:
Converted amount equates to: 3 quarters 1 dime 0 nickels 4 pennies
Is there a more efficient (fewer lines of code or a better OO style) way to implement this?
nickelUnit = nickels==1 ? " nickel" : (nickels==0||nickels>1 ? " nickels" : "ERROR - negative amount of nickels!");
but I'm not sure you'd really gain much from that. \$\endgroup\$