我有一个小任务,我必须使用二维数组产生帕斯卡三角。这是我的code,和它的作品。有一个额外的信贷机会,如果我显示,像这样的三角:
I have a small assignment where I have to use a 2d array to produce Pascal's triangle. Here is my code, and it works. there is an extra credit opportunity if I display the triangle like so:
不过,我的间距没有格式化这样。它只是显示所有列队在左边的数字。它很难形容,但如果你运行它,你会明白我的意思。
however, my spacing is not formatted like that. it simply displays the numbers all lined up on the left. its hard to describe but if you run it you will see what I mean.
这是我的code:
import java.util.*;
public class Pascal {
public static final int ROW = 16;
public static void main(String[] args) {
int[][] pascal = new int[ROW +1][];
pascal[1] = new int[1 + 2];
pascal[1][1] = 1;
for (int i = 2; i <= ROW; i++) {
pascal[i] = new int[i + 2];
for (int j = 1; j < pascal[i].length - 1; j++) {
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
}
}
for (int i = 1; i <= ROW; i++) {
for (int j = 1; j < pascal[i].length - 1; j++) {
System.out.print(pascal[i][j] + " ");
}
System.out.println();
}
}
}
如果有人可以帮助我弄清楚如何正确的间距添加到我的程序来产生所需的图像输出,这将是巨大的:)我知道我需要把系统绝版,地方我只是不知道在哪里。谢谢!
if someone could help me figure out how to add the correct spacing to my program to produce the output desired in the picture, that would be great :) I know I need to put a system out print " " somewhere I just dont know where. thanks!
推荐答案
在这里,我已经修改了code,它打印奇妙的行大小,直到13日,我的控制台窗口的限制,表兄弟姐妹。
Here I had modified your code, it prints wonderfully for ROW size till 13, coz of the limitation of my console window.
import java.util.*;
public class Pascal {
public static final int ROW = 12;
private static int max = 0;
public static void main(String[] args) {
int[][] pascal = new int[ROW +1][];
pascal[1] = new int[1 + 2];
pascal[1][1] = 1;
for (int i = 2; i <= ROW; i++) {
pascal[i] = new int[i + 2];
for (int j = 1; j < pascal[i].length - 1; j++) {
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
String str = Integer.toString(pascal[i][j]);
int len = str.length();
if (len > max)
max = len;
}
}
for (int i = 1; i <= ROW; i++) {
for (int k = ROW; k > i; k--)
System.out.format("%-" + max + "s", " ");
for (int j = 1; j < pascal[i].length - 1; j++)
System.out.format("%-" + (max + max) + "s", pascal[i][j]);
System.out.println();
}
}
}
希望这可以帮助。
Hopefully this might help.
问候
相关推荐
最新文章