gpt4 book ai didi

java - System.out.printf() 有没有办法接受变量来设置字段宽度?

转载 作者:行者123 更新时间:2023-11-30 03:47:25 25 4
gpt4 key购买 nike

我正在尝试向控制台显示金字塔,如下所示:

          1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1

到目前为止,我的想法是在每行之前打印预设数量的空格。

我想出的公式非常简单:numberOfSpaces = (totalRows - currentRow) * 2。例如,第一列有10 个空格。这10个空格位于金字塔底部的“6”和金字塔顶部的“1”之间。每增加一行,空格数就会减少 2。

问题就出在这里。我无法弄清楚 System.out.printf() 方法 在设置字段时接受变量 numberOfSpaces 的正确语法(或其存在)宽度。在最右对齐的上下文中,该字段宽度将允许我打印每行中的空格。

这是我到目前为止编写的代码。虽然没有编译错误,但我知道逻辑上可能有很多错误。

    public class DisplayPattern {
public static void main (String[] args) {

// Displays Pattern A.
int integerPosition = 1;
for (int x = 1; x <= 6; x++) {
for (int y = 1; y <= integerPosition; y++)
System.out.print(y + " ");
integerPosition++;
System.out.println();
}
System.out.println();

// Displays Pattern B.
integerPosition = 6;
for (int x = 1; x <= 6; x++) {
for (int y = 1; y <= integerPosition; y++)
System.out.print(y + " ");
integerPosition--;
System.out.println();
}
System.out.println();

// Displays Pattern C.
int totalRows = 6;
int currentRow = 1;

for (int x = 1; x <= 6; x++) {
int numberOfSpaces = (totalRows - currentRow) * 2;
for (int y = 1; y <= integerPosition; y++)
System.out.printf("%(int)(numberOfSpaces)d", y);
integerPosition++;
currentRow++;
System.out.println();
}
System.out.println();
}
}

最令人担忧的是 C 部分。A 部分和 B 部分均不包含空格,不会造成任何问题。

http://i.imgur.com/wK4csvv.gif

很抱歉无法在此处直接托管图像;作为新用户,我显然没有足够的声誉。

感谢您帮助初学者和业余程序员!

最佳答案

您将变量的名称放入格式字符串中。您只需使用变量的值构建字符串,如下所示:

System.out.printf("%" + numberOfSpaces + "d", y);

严格来说,格式中的数字(%d 之间)代表整个数字表示形式,因此它包括空格和位数您的数字y,因此您必须计算它并添加它:

System.out.printf("%" + (numberOfSpaces + nbOfDigitsOfY) + "d", y);

旁注:如果你想要的是对齐,我认为你比单独计算空格数和位数更容易计算最终结果。

关于java - System.out.printf() 有没有办法接受变量来设置字段宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25297659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com