I'm wondering if there is a way to simplify this program.

I feel like I wasted a lot of time on all the ternary codes at the bottom for labeling "bill" for the three values (ten\$, five\$, and one\$).

Also for deriving the values for q,d,n, and p I feel like I was being redundant for no reason. -_-

``````/*This project will prompt for a valid double value for cash and
determine the fewest number of bills and coins needed to reflect
this value.*/
import java.util.Scanner;
import java.text.DecimalFormat;

public class Project9
{
public static void main (String[]args)
{
int ten\$,five\$,one\$,q,d,n,p;
double total;

Scanner scan = new Scanner (System.in);
DecimalFormat money = new DecimalFormat ("0.00");
DecimalFormat integer = new DecimalFormat ("0");

System.out.println("Please enter a value for cash: " );
total = scan.nextDouble();

ten\$ = (int) total / 10;
five\$ = (int) (total % 10) / 5;
one\$ = (int) total % 10 % 5;
q = (int) (total % 1 / .25);
d = (int) (total % 1 % .25 / .10);
n = (int) (total % 1 % .25 % .10 / .05);
p = (int) (total % 1 % .25 % .10 % .05 / .01);

String lbl1 = "bill" + ((ten\$ > 1) ? "s":"");
String lbl2 = "bill" + ((five\$ > 1) ? "s":"");
String lbl3 = "bill" + ((one\$ > 1) ? "s":"");

System.out.println(ten\$ + " ten dollar " + lbl1);
System.out.println(five\$ + " five dollar " + lbl2);
System.out.println(one\$ + " one dollar " + lbl3);
System.out.println(q + " quarters");
System.out.println(d + " dimes");
System.out.println(n + " nickels");
System.out.println(p + " pennies");
}
}``````

## All 3 Replies

deriving the values for q,d,n, and p

Single letter variable names are a poor technique. Use full words for variable names.

Put it all where you want it:

``(ten\$ + " ten dollar bill" + ((ten\$ > 1) ? "s":"")));``

You've helped yet again NormR1. Thanks. Note taken. No more single letter variables.

Single letter variable names are a poor technique. Use full words for variable names.

Put it all where you want it:

``(ten\$ + " ten dollar bill" + ((ten\$ > 1) ? "s":"")));``

You can simplify this program massively in an OO way by creating a class for the bills/coins. Each instance has a value and a name. You have an array of those representing all the various bills and coins you can use. Then most of your repeated code comes down to a simple loop that loops through them.
If you're not ready for creating new objects yet you can use an array of bill/coin values and a parallel array of bill/coin names.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.