5
\$\begingroup\$

I have written a program that takes in some amount of money, and prints the equivalent change (starting at hundred dollars, to fifty, to twenty, down the pennies). Here is the code:

System.out.print("Enter amount of money: ");
Scanner scan = new Scanner(System.in);

double value = scan.nextDouble();
int valueIntegral = (int) value;
int valueFractional = (int) Math.round(100 * value - 100 * valueIntegral);

// Integral values

int hundred = valueIntegral / 100;

int fifty = (valueIntegral % 100) / 50;

int twenty = ((valueIntegral % 100) % 50) / 20;

int ten = (((valueIntegral % 100) % 50) % 20) / 10;

int five = ((((valueIntegral % 100) % 50) % 20) % 10) / 5;

int one = (((((valueIntegral % 100) % 50) % 20) % 10) % 5) / 1;

// Fractional values

int quarter = valueFractional / 25;

int dime = (valueFractional % 25) / 10;

int nickel = ((valueFractional % 25) % 10) / 5;

int penny = (((valueFractional % 25) % 10) % 5) / 1;

System.out.println(hundred + " hundred dollar bills\n" +
                   fifty + " fifty dollar bills\n" +
                   twenty + " twenty dollar bills\n" +
                   ten + " ten dollar bills\n" +
                   five + " five dollar bills\n" +
                   one + " one dollar bills\n" +
                   quarter + " quarters\n" +
                   dime + " dimes\n" +
                   nickel + " nickels\n" +
                   penny + " pennies");

What I want to know is that without using loops or any iterative structures is this an acceptable way to accomplish this task? What would be a more elegant way? (those chains of modulo division are ugly)

\$\endgroup\$
5
\$\begingroup\$

Without loops or similar "advanced" structures, there isn't much you can do to simplify this.

You could save the duplication in extra variables. It might look like this:

int hundred = valueIntegral / 100;

int remainderHundred = valueIntegral % 100;
int fifty = remainderHundred / 50;

int remainderFifty = remainderHundred % 50;
int twenty = remainderFifty / 20;

int remainderTwenty = remainderFifty % 50;
int ten = remainderTwenty / 10;

[...]

You have to decide if it's more readable. It's certainly less complex (and mistakes/typos are easier to catch), but it might take away some clarity.

Misc

  • you have a bit too much vertical space. Not every line needs its own paragraph.
  • your comments don't add all that much value. The variable names already tell me all the comments do.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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