简体   繁体   English

如何使用printf将单独的字符串格式化为一行?

[英]How do I use printf to format separate strings into one line?

I am using a while loop and getting data from a text file and using classes to reference each string. 我正在使用while循环并从文本文件获取数据,并使用类来引用每个字符串。 I don't have any issues getting the values for each string and printing it out. 我没有任何问题获取每个字符串的值并将其打印出来。

However, I am confused on how to use System.out.printf(....) to put all of the strings I need in one line while using a loop. 但是,我对如何使用System.out.printf(....)在使用循环时将所需的所有字符串放在一行中感到困惑。

For example, let's say the text file was: 例如,假设文本文件为:

I 一世
like 喜欢
to
use 采用
computers 电脑

I want to use a loop to print out the words into one string and I may have different spacing between each word. 我想使用循环将单词打印成一个字符串,并且每个单词之间的间距可能不同。

The code I have so far: 我到目前为止的代码:

while (!readyOrder.isEmpty()) {
    s = readyOrder.poll();
    System.out.printf(s.getQuantity() + " x " + s.getName()
        + "(" + s.getType() + ")" + "                "
        + s.getPrice() * s.getQuantity());
    System.out.println(" ");
    total = total + s.getPrice() * s.getQuantity();
}

And the output should be: 输出应为:

1_x_The Shawshank Redemption_______(DVD)________________19.95 1_x_肖申克的救赎_______(DVD)________________ 19.95

The underlined spaces are where the spaces should be and how long they should be. 带下划线的空格是空格应位于的位置,以及空格应位于的位置。

How can I use printf to do that? 如何使用printf做到这一点?

I think you need to use the string padding functionality of printf. 我认为您需要使用printf的字符串填充功能。 For example %-30s formats to width of 30 characters, - means left justify. 例如%-30s格式为30个字符的宽度,-表示左对齐。

for (Stock s : Arrays.asList(
        new Stock(1, "The Shawshank Redemption", 100, "DVD"), 
        new Stock(2, "Human Centipede", 123, "VHS"),
        new Stock(1, "Sharknado 2", 123, "Blu ray"))) {

    System.out.printf("%2d x %-30s (%-7s) %5.2f\n",
            s.getQuantity(), s.getName(), s.getType(),
            s.getPrice() * s.getQuantity());
}

Output 产量

1 x The Shawshank Redemption       (DVD    ) 100.00
2 x Human Centipede                (VHS    ) 246.00
1 x Sharknado 2                    (Blu ray) 123.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM