1

For a class, I have to input a number of quarters, dimes, and nickels and output them as dollars.

If I input 4 quarters, 10 dimes, and 5 nickels, I get $225.00, not $2.25.

Can anyone help me, please?

public static void main(String[] args) {

    System.out.print("Enter Number of Quaters: ");
    Scanner quarter = new Scanner (System.in);
    int quarters = quarter.nextInt();

    System.out.print("Enter Number of Dimes: ");
    Scanner dime = new Scanner (System.in);
    int dimes = dime.nextInt();

    System.out.print("Enter Number of Nickels: ");
    Scanner nickel = new Scanner (System.in);
    int nickels = nickel.nextInt();

    DecimalFormat df = new DecimalFormat("$0.00");
    System.out.print("The total is ");
    System.out.println(df.format((quarters * 25) + (dimes * 10) + (nickels * 5)));
}
0xCursor
  • 2,242
  • 4
  • 15
  • 33
Sarid Ruiz
  • 43
  • 1
  • 11
  • I didn't check but I'm sure decimal format requires a decimal, not an `int`. Convert to `double`, then format. – markspace Oct 01 '18 at 00:22
  • you have to divide ((quarters * 25) + (dimes * 10) + (nickels * 5)) by 100. You converted everything to cents and expecting dollars. – Ashraff Ali Wahab Oct 01 '18 at 00:26
  • 2
    Also look at this answer, fourth answer down the list uses a currency format: https://stackoverflow.com/questions/2379221/java-currency-number-format (Re. @AshraffAliWahab answer, you have to divide by `100.0`, not 100, which will still give you an `int`.) – markspace Oct 01 '18 at 00:27
  • Have you learned how to use `.printf` yet? Using %.2d in conjunction with / 100.0 is probably what your Prof. is looking for. – John Oct 01 '18 at 01:16

1 Answers1

1

I know the following code is pretty hacky but if you don't have to use DecimalFormat, then this should format an int value representing cents to dollars, correctly:

int total = (quarters * 25) + (dimes * 10) + (nickels * 5);
String strTotal = (total<10 ? "0" + String.valueOf(total) : String.valueOf(total));
String formattedTotal = "$" + (strTotal.length()<3 ? "0" : strTotal.substring(0, strTotal.length()-2))
                            + "." + strTotal.substring(strTotal.length()-2, strTotal.length());

System.out.println(formattedTotal);
0xCursor
  • 2,242
  • 4
  • 15
  • 33