Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use formatting with printf correctly in Java

Tags:

java

printf

I'm trying to create a simple program to take in three items, their quantities, and prices and added them all together to create a simple receipt type format. My professor gave me a specific format for the receipt where all the decimals line up and are consistently placed. It should look like this.

Your Bill:


Item                           Quantity       Price         Total
Diet Soda                            10        1.25         12.50
Candy                                1         1.00          1.00
Cheese                               2         2.00          4.00


Subtotal                                                    17.50
6.25% Sales Tax                                              1.09
Total                                                       18.59

My professor specified there should be 30 characters for the name, 10 for quantity and price and total. Doing this I have to use the printf method. I'm trying to format it with this code so far.

import java.util.Scanner;
class AssignmentOneTest {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);

        // System.out.printf("$%4.2f for each %s ", price, item);
        // System.out.printf("\nThe total is: $%4.2f ", total);

        // process for item one
        System.out.println("Please enter in your first item");
        String item = kb.nextLine();
        System.out.println("Please enter the quantity for this item");
        int quantity = Integer.parseInt(kb.nextLine());
        System.out.println("Please enter in the price of your item");
        double price = Double.parseDouble(kb.nextLine());

        // process for item two
        System.out.println("Please enter in your second item");
        String item2 = kb.nextLine();
        System.out.println("Please enter the quantity for this item");
        int quantity2 = Integer.parseInt(kb.nextLine());
        System.out.print("Please enter in the price of your item");
        double price2 = Double.parseDouble(kb.nextLine());
        double total2 = quantity2 * price2;
        // System.out.printf("$%4.2f for each %s ", price2, item2);
        // System.out.printf("\nThe total is: $%4.2f ", total2);

        // process for item three
        System.out.println("Please enter in your third item");
        String item3 = kb.nextLine();
        System.out.println("Please enter the quantity for this item");
        int quantity3 = Integer.parseInt(kb.nextLine());
        System.out.println("Please enter in the price of your item");
        double price3 = Double.parseDouble(kb.nextLine());
        double total3 = quantity3 * price3;
        // System.out.printf("$%4.2f for each %s ", price3, item3);
        // System.out.printf("\nThe total is: $%4.2f ", total3);

        double total = quantity * price;

        double grandTotal = total + total2 + total3;
        double salesTax = grandTotal * (.0625);
        double grandTotalTaxed = grandTotal + salesTax;

        String amount = "Quantity";
        String amount1 = "Price";
        String amount2 = "Total";
        String taxSign = "%";

        System.out.printf("\nYour bill: ");
        System.out.printf("\n\nItem");
        System.out.printf("%30s", amount);
        // System.out.printf("\n%s %25d %16.2f %11.2f", item, quantity, price,
        // total);
        // System.out.printf("\n%s %25d %16.2f %11.2f", item2,quantity2, price2,
        // total2);
        // System.out.printf("\n%s %25d %16.2f %11.2f", item3,quantity3, price3,
        // total3);

        System.out.printf("\n%s", item);
        System.out.printf("%30d", quantity);
        System.out.printf("\n%s", item2);
        System.out.printf("\n%s", item3);

        System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
        System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
        System.out.printf("\nTotal %50.2f", grandTotalTaxed);    
    }
}

If I enter in a longer item name, it moves the placement of quantity and price and total. My question is, how do I make a set start point with a limited width using printf, please help.

like image 204
user1808763 Avatar asked Jan 19 '13 09:01

user1808763


People also ask

What is %s and %D in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What method do you use for formatted printing in Java?

printf() method is not only there in C, but also in Java. This method belongs to the PrintStream class. It's used to print formatted strings using various format specifiers.

Why do we use %d in Java?

%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.


1 Answers

System.out.printf("%1$-30s %2$10d %3$10.2f %4$10.2f", "Diet Soda", 10, 1.25, 12.50);

Will print the line

Diet Soda                              10       1.25      12.50

The first string passed to the printf method is a series of format specifiers that describe how we want the rest of the arguments to be printed. Around the format specifiers you can add other characters that will also be printed (without being formatted).

The format specifiers above have the syntax:
%[index$][flags][width][.precision]conversion where [] denotes optional.

% begins a formatting expression.

[index$] indicates the index of the argument that you want to format. Indices begin at 1. The indices above are not actually needed because each format specifier without an index is assigned one counting up from 1.

[-] The only flag used above, aligns the output to the left.

[width] indicates the minimum number of characters to be printed.

[.precision] In this case the number of digits to be written after the decimal point, although this varies with different conversions.

conversion character(s) indicating how the argument should be formatted. d is for decimal integer, f is decimal format for floating points, s doesn't change the string in our case.

More information can be found here.

like image 168
Alex - GlassEditor.com Avatar answered Sep 21 '22 12:09

Alex - GlassEditor.com