我想在控制台中美化我的版本。 我现在怎样才能像在表格中一样写下整个内容呢? 我尝试过用空格进行计数,但随着值的变化,情况非常糟糕。您知道如何美化它们之间的问题吗?
我的代码:
private static void berechneVerbrauch(Tankbeleg[] tanken) {
System.out.print("Datum" + " KM-Stand" + " Liter" + " Preis" + " Verbrauch");
System.out.println(" ");
for (int i = 0; i < tanken.length; i++) {
System.out.print(tanken[i].datum + " " + tanken[i].kmStand + " " + tanken[i].getankteLiter + " " + tanken[i].literPreis+ " " );
System.out.println(" ");
}
}
提前谢谢
最诚挚的问候 迈克尔
编辑
private static void berechneVerbrauch(Tankbeleg[] tanken) {
System.out.print("Datum" + "\tKM-Stand" + "\tLiter" + "\tPreis" + "\tVerbrauch");
System.out.println(" ");
for (int i = 0; i < tanken.length; i++) {
//System.out.printf("%s %s %s %s", tanken[i].datum, tanken[i].kmStand, tanken[i].getankteLiter, tanken[i].literPreis);
System.out.print(tanken[i].datum + "\t" + tanken[i].kmStand + "\t" + tanken[i].getankteLiter + "\t" + tanken[i].literPreis+ "\t" );
System.out.println(" ");
}
}
最佳答案
使用System.out.printf()
。 printf 是格式化打印,因此您可以声明每个变量有多少个空格,根据需要截断或扩展变量。请参阅tutorials for printf()了解如何使用它。
就您而言,这样的内容可能适合标题:
System.out.printf("%10s %8s %5s %5s %9s", "Datum", "KM-Stand", "Liter", "Preis", "Verbrauch");
对于数据线:
System.out.printf("%10s %8s %5s %5s", tanken[i].datum, tanken[i].kmStand, tanken[i].getankteLiter, tanken[i].literPreis );
我编写了一个像这样的主要方法来模拟代码,以便我可以看到格式
public static void main(String[] args){
System.out.printf("%10s %8s %5s %5s %9s", "Datum", "KM-Stand", "Liter", "Preis", "Verbrauch");
System.out.println(" ");
for (int i = 0; i < args.length; i++) {
System.out.printf("%10s %8s %5s %5s", args[0], args[1], args[2], args[3] );
System.out.println(" ");
}
}
::输出::
$ java Test 20.05.2010 30000 20 30
Datum KM-Stand Liter Preis Verbrauch
20.05.2010 30000 20 30
20.05.2010 30000 20 30
20.05.2010 30000 20 30
20.05.2010 30000 20 30
$ java Test alpha beta cala baza
Datum KM-Stand Liter Preis Verbrauch
alpha beta cala baza
alpha beta cala baza
alpha beta cala baza
alpha beta cala baza
您可以使用 printf
选项使它们左对齐或填充除空格之外的其他字符,这是一个非常有用的工具
关于java - "Beautify"Java控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47225815/