如何在保持列组织的同时使用printf函数?

时间:2015-10-15 08:23:49

标签: java printf stringbuilder

我正在尝试在java中为项目打印发票报告,但我在格式化工作表时遇到了问题。这是我遇到问题的代码。

btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                Toast.makeText(MainActivity.this, "ACTION_UP", Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    });

打印出来

StringBuilder sb = new StringBuilder(); 
sb.append(String.format("%s%s%-82s%s%10.2f%s","DISCOUNT ( ","Placeholder"," )", "$", 99.99, "\n"));

如果我更改“占位符”一词的字符长度,则会移动$ 99.99列。

DISCOUNT ( Placeholder )                                                                                $     99.99

我需要做的代码是“占位符”一词是否被替换为10个字符长或1个字符长的单词,99.99美元需要保留在同一个地方,以便在打印时它位于正确的列中。我尝试修改$ s的$ s,但如果更改占位符,它似乎仍然会移动。建议?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用width参数 像这样的东西(这里的宽度是15):

System.out.printf("%s%15s%-82s%s%10.2f%s", "DISCOUNT ( ", "Placeholder", " )", "$", 99.99, "\n");

不确定String.format是否使用与printf完全相同的语法。

输出将是:

DISCOUNT (     Placeholder )                                           $     99,99
DISCOUNT (               p )                                           $     99,99

答案 1 :(得分:0)

您可以通过从特定值中减去占位符的长度来计算格式的长度。

private static String placeHolder = "";
private static int value;

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder(); 
    setPlaceHolder("");
    sb.append(String.format("%s%s%-"+value+"s%s%10.2f%s","DISCOUNT ( ",placeHolder," )", "$", 99.99, "\n"));
    setPlaceHolder("Placeholder");
    sb.append(String.format("%s%s%-"+value+"s%s%10.2f%s","DISCOUNT ( ",placeHolder," )", "$", 99.99, "\n"));
    setPlaceHolder("This is quite some long text");
    sb.append(String.format("%s%s%-"+value+"s%s%10.2f%s","DISCOUNT ( ",placeHolder," )", "$", 99.99, "\n"));
    System.out.println(sb);
}

private static void setPlaceHolder(String placeholder) {
    placeHolder = placeholder;
    value = 83 - placeholder.length();
}

输出

DISCOUNT (  )                                                                                 $     99,99
DISCOUNT ( Placeholder )                                                                      $     99,99
DISCOUNT ( This is quite some long text )                                                     $     99,99