概述
我确定这对你们大多数人来说都是一个简单的问题,但是我一直在努力解决一个小间距问题,并希望我可以向更有经验的人学习。我需要生成一个类似下面的三角形。无论长度如何,您都可以看到数字正确对齐。
Enter the number of lines: 8
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
我的代码
这是我到目前为止所拥有的。它并不是最漂亮的,但它似乎至少给了我正确的价值。
import java.util.Scanner;
public class Pyramid2
{
public static void main(String[] args)
{
int i, j, k, l, a;
//Create a Scanner object
Scanner in = new Scanner (System.in);
//Prompt the user to enter number of rows in pyramid
System.out.print("Enter number of rows: ");
int rows = in.nextInt();
a = rows;
//Variables to determine length
int length = ("" + rows).length();
String str = " %" + length + "s";
//Logic
for (i = 1; i <= rows; i++)
{
for (j = a; j > 0; j--)
{
System.out.printf(str, " ");
}
for (j = 1; j <= (2*rows); j++)
{
if (j == (rows+1))
{
continue;
}
if (j < (rows+1))
{
k = j;
}
else
{
k = ((2*rows)-j+1);
}
if (k >= (rows+1-i))
{
l = (int)Math.pow(2, (i+k-rows-1));
String str1 = "" + l;
System.out.printf(str, str1);
}
}
a--;
System.out.println();
}
}
}
我的结果
这是选择6行时的控制台输出。在第5行出现2位数字(16)时,一切看起来都很好。有哪些有效的方法可以正确对齐结果?
Enter number of rows: 6
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
答案 0 :(得分:3)
首先,我可以建议确定金字塔中的最大数字。然后计算此数字中的数字。对于8行,这个数字是128,它有3位数。根据这些信息,我们可以决定我们需要3 + 1 = 4(包括空格)字符来打印金字塔中的每个值。 之后,您必须按空格(从左侧)到4个字符的最终字符串大小完成每个输出编号。 每个金字塔线的全局前缀将包含(rows - i)* 4个空格。
答案 1 :(得分:3)
您将length
计算为rows
中的位数,但它必须是三角形中最大数字的位数。
E.g。对于rows = 6
,最大号码为32
,因此length
应为2
。
对于rows = 8
,最大的数字为128
,因此length
应为3
。
最大数字是2 行,在Java中表示1 << rows
,因此将length
计算更改为:
int length = ("" + (1 << rows)).length();
你还在左边添加了太多空格。
将代码更改为:
a = rows - 1;