88.5k views
5 votes
JAVA Assume that price is an integer variable whose value is the price (in US currency) in cents of an item. Write a statement that prints the value of price in the form "X dollars and Y cents" on a line by itself. So, if the value of price was 4321, your code would print "43 dollars and 21 cents". If the value was 501 it would print "5 dollars and 1 cents". If the value was 99 your code would print "0 dollars and 99 cents".

1 Answer

3 votes

Answer:

System.out.printf("%d%s%d%s", price/100, " dollars and " , price%100, "cents");

Step-by-step explanation:

First thing first, convert the price.

i. Divide the price value by 100 to get the number of dollars in the price value. That is, price/100.

ii. Find the modulus (or remainder) of the price value with 100 to get the number of cents in the price value. That is, price%100

Next, to print out the value in the form "X dollars and Y cents", the Java's function System.out.printf() could be used.

The printf() allows us to specify formatting styles for our data.

To print a data of type String, the format specifier is %s

To print a data of type int, the format specifier is %d.

The output, "X dollars and Y dollars", contains String and int data type. X and Y are integers. Others are strings. So, the %s and %d format specifiers will suffice.

Putting all these together, we have

System.out.printf("%d%s%d%s", price/100, " dollars and " , price%100, "cents");

Hope this helps!

User Andyb
by
5.2k points