简体   繁体   中英

Dollars and Cents (JAVA)

I need help with the calucluations for this java project i'm working on. The assignment asks me write a program that will spell out the number of dollars & cents based on a user numeric input. So, basically, the person enters a number like 815. and the program should output "8 dollars and 15 cents").

This is the code I have so far.

UPDATED again

public class DollarCents
{

    public static void main(String args [])
    {
        // Declaration of variables.
       int dollars;
       int cents;
       String inputNumberString;
       int inputNumber;
       int calculatedAnswer;

       // Get interactive user input
       inputNumberString = JOptionPane.showInputDialog("Enter Cents: ");

       // Convert String to int
       inputNumber = Integer.parseInt(inputNumberString);

       // Calculate the number
       dollars = inputNumber / 100;
       cents = inputNumber % 100;

       // Output the result
       System.out.println ("The Cents entered equal: $"+ dollars +"."+ cents);
    }
}

Hint: use String.split() and split on the decimal separator.

Everything that comes before it you can output as a dollar, and everything after it you can output as a cent. I'll leave the 0 dollar/cent situation as an exercise to the OP.

Note: I assumed the input will be 8.15 and the output should be as you stated. If you meant to input 815 and have the last two digits interpreted as cents, then you will need to use String.length() and String.substring .

would something like this work for you?

// Calculate the number  
double amount = ((double)inputNumber) /100;

// Output the result
String output = NumberFormat.getCurrencyInstance().format(amount);

The actual code included in the question is wrong! (version 9)

If you enter 5 (so 5 cents), the output will be:

The Cents entered equal: $0.5

The user win or loose 45 cents in the process! The cents must be formatted:

System.out.println ("The Cents entered equal: $"+ dollars +"."+ String.format("%02d", cents));

Note: this post should be a comment but I am not allowed to do so

I assume your program will need to turn 101516 into "One hundred and one thousand, five hundred and sixteen dollars"? You need to use the % modulus operator a lot!

Hint: Build lookup tables of text, but be aware that you will have lots of special cases.

EG

String[] TensHundreds = {
  "No", "One", "Two", "Three", ...
  "Eleven", "Twelve", "Thirteen", ...
  /* Do we really have to list all next eighty??? */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM