所以这是我需要格式化的代码片段:
double textbookprice = 0, tradebookprice = 0;
for(int i=0;i<tempTextbooks.size();i++) {
System.out.println(tempTextbooks.get(i).dataMember +"\t "+tempTextbooks.get(i).title +"\t "+tempTextbooks.get(i).author+"\t $"+df.format(tempTextbooks.get(i).getPrice()));
textbookprice = textbookprice + tempTextbooks.get(i).getPrice();
}
这就是我得到的输出,
COS221 Introduction to Programming with C++ Y. Daniel Liang $120.99
COS225 Java Foundations John Lewis $94.59
BUS398 Excel 2010 Power Programming with VBA John Walkenbach $87.99
我需要班级编号/标题/作者/价格都有自己的专栏
答案 0 :(得分:3)
您可以使用System.out.format来定义字段的长度。像这样的东西
System.out.format("%-10s %-40s %-20s %-15s \n", tempTextbooks.get(i).dataMember, tempTextbooks.get(i).title, tempTextbooks.get(i).author, df.format(tempTextbooks.get(i).getPrice()));
这会将前四列的宽度修复为10,40,20和15个字符。它们之前的-
表示您希望它们保持对齐。 (如果您想要右对齐表,可以删除-
。)
您可以根据自己的要求进行更改。
修改强>
我尝试使用此代码重现此问题
public class HelloWorld {
public static void main(String[] args) {
String[] s1 = {"COS221", "COS225", "BUS398"};
String[] s2 = {"Introduction to Programming with C++", "Java Foundations", "Excel 2010 Power Programming with VBA"};
String[] s3 = {"Y. Daniel Liang", "John Lewis", "John Walkenbach"};
String[] s4 = {"$120.99", "$94.59", "$87.99"};
for (int i = 0; i < 3; i++) {
System.out.format("%-10s %-40s %-20s %-15s \n", s1[i], s2[i], s3[i], s4[i]);
}
}
}
输出如下:
COS221 Introduction to Programming with C++ Y. Daniel Liang $120.99
COS225 Java Foundations John Lewis $94.59
BUS398 Excel 2010 Power Programming with VBA John Walkenbach $87.99