String.format builds text from a template: %d is a whole number, %s any value, %5d pads to five characters on the left, %-8s pads text to eight on the right, and %03d pads with zeros. String.format("%-8s%5d", "Tea", 250) is "Tea 250". (System.out.printf prints the same way.)
Money is best kept in cents as an int, then shown as dollars and cents with integer division and remainder: cents / 100 dollars and cents % 100 cents, the cents zero-padded to two digits. Doing it with %02d avoids floating-point rounding surprises, and this runtime has no %f, so it is also the way that works here.
String line = String.format("%-10s%6s", "Coffee", "$3.25");
System.out.println(line); // Coffee $3.25Your task
Write static String money(int cents) returning $<dollars>.<cents> with two cent digits (money(250) is "$2.50", money(7) is "$0.07"), static String padRight(String text, int width) returning the text padded with spaces on the right to the width (unchanged when already longer), and static String receiptLine(String item, int cents) returning the item padded to 12 characters followed by the money padded on the left to 8 characters, so receiptLine("Tea", 250) is "Tea $2.50".
Hint 1
return String.format("$%d.%02d", cents / 100, cents % 100);
Hint 2
padRight: String.format("%-" + width + "s", text). receiptLine: padRight(item, 12) + String.format("%8s", money(cents)).
Show the solution
public class Main {
static String money(int cents) {
return String.format("$%d.%02d", cents / 100, cents % 100);
}
static String padRight(String text, int width) {
return String.format("%-" + width + "s", text);
}
static String receiptLine(String item, int cents) {
return padRight(item, 12) + String.format("%8s", money(cents));
}
public static void main(String[] args) {
System.out.println(receiptLine("Tea", 250));
System.out.println(receiptLine("Sandwich", 1275));
}
}