如何在Java中正确使用printf格式化 [英] How to use formatting with printf correctly in Java

查看:42
本文介绍了如何在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

我的教授指定名称应包含30个字符,数量,价格和总计应包含10个字符.为此,我必须使用printf方法.到目前为止,我正在尝试使用此代码对其进行格式化.

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);    
    }
}

如果输入较长的项目名称,它将移动数量,价格和总计的位置.我的问题是,如何使用printf来设置一个有限宽度的起点,请帮忙.

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.

推荐答案

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

将打印行

Diet Soda                              10       1.25      12.50

传递给 printf 方法的第一个字符串是一系列格式说明符,描述了我们希望如何打印其余参数.在格式说明符周围,您可以添加也会打印(不格式化)的其他字符.

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).

上面的格式说明符具有以下语法:
%[index $] [flags] [width] [.precision] conversion ,其中 [] 表示可选.

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

开始格式化表达式.

[index $] 表示要设置格式的参数的索引.索引从1开始.实际上不需要上面的索引,因为没有索引的每个格式说明符都从1开始递增计数.

[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] 表示要打印的最小字符数.

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

[.precision] 在这种情况下,小数点后要写入的位数,尽管随着转换的不同而有所不同.

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

转换字符,指示应如何设置自变量的格式. d 是十进制整数, f 是浮点十进制格式,在我们的情况下, s 不会更改字符串.

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.

更多信息,请参见此处.

这篇关于如何在Java中正确使用printf格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆