在输出前留下特定的间隙

uemypmqf  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(286)

我想在打印文本之前留下一定数量的空白
如果我很可爱:

System.out.printf("Some Text : ");
for (int stars = 0; stars < 5; stars++) { 
    System.out.print("*");
} 
System.out.println();

System.out.printf("Some Bigger Text : ");
for (int stars = 0; stars < 3; stars++) {
    System.out.print("*");
} 
System.out.println();

我会得到结果:

Some Text :*****
Some Bigger Text :***

但我想要的是

Some Text        :*****
Some Bigger Text :***

注意:我不想做这样的事 System.out.printf("Some Text : "); 还有别的办法吗?
谢谢你的帮助!

nzrxty8p

nzrxty8p1#

您可以使用printf的格式

package com.stackoverflow.question;

public class Main {

    public static void main(String[] args) {
        System.out.printf("%-30s : ", "Some Text"); //Justify left
        for (int stars = 0; stars < 5; stars++) { 
            System.out.print("*");
        } 
        System.out.println();

        System.out.printf("%-30s : ", "Some Bigger Text"); //Justify left
        for (int stars = 0; stars < 3; stars++) {
            System.out.print("*");
        } 
        System.out.println();
    }

}

输出

Some Text                      :*****
Some Bigger Text               :***

其他信息-此处

qxgroojn

qxgroojn2#

您只需将缩进添加到system.out.printf()语句中

System.out.printf("Some Text");
System.out.printf("%-20s",":");
for (int stars = 0; stars < 5; stars++) { 
    System.out.print("*");
} 
System.out.println();

System.out.printf("Some Bigger Text ");
System.out.printf("%-20s",":");
for (int stars = 0; stars < 3; stars++) {
    System.out.print("*");
} 
System.out.println();

输出如下所示:

Some Text                  :*****
Some Bigger Text           :***
pu82cl6c

pu82cl6c3#

您可以搜索最长的文本(长度),然后将缺少的空格添加到其他文本行。。。

相关问题