我制作了一个应用程序,它接受一些值并将它们添加到一个 txt 文件中。 它做这样的事情,它们是 strings[] :
product[1] quantity[1] price[1]
product[2] quantity[2] price[2]
.....
product[n] quantity[n] price[n]
问题是,大多数时候产品 [1] 的长度与产品 [2] 或其他产品的长度不同,数量和价格也是如此。这会导致文本布局困惑,例如这个。
ww 2 4
wwww 1 2.5
w 1.2 1.1
有什么方法可以让它更整洁吗?像创建表或列之类的东西? 谢谢!
编辑:为了让它更清楚一点,我想找到一种方法来排列 txt 文件中的内容,而不是上面示例中的内容
ww 2 4
wwww 1 2.5
w 1.2 1.1
目前我正在使用这个 pw.println(prod[n]+""+cant[n]+""+pret[n]);} 但这会使 txt 文件中的文本未对齐(示例 1)
最佳答案
像这样使用 String
类的 format
方法:
使用以下格式声明一个字符串
String yourFormat = "%-10s %-10s %-10s%n"; //choose optimal ranges.
//if you exceed them, it will always automatically make one space
//between the next column
用该格式写输出:
output.write(String.format(yourFormat, firstString, secondString, thirdString));
第一个字符串是你的 w,第二个和第三个是带有数字的列。
以你的例子为例:
String myFormat = "%-10s %-10s %-10s%n";
for(int i=0;i<prod.length();i++){
pw.println(String.format(myFormat, prod[n], cant[n], pret[n]));
}
关于java - 在保存的 txt 文件中排列文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076783/