我写我自己的逻辑来打印pascal三角形。有以下代码:为什么我的pascal三角形程序没有给出正确的格式?
import java.util.Scanner;
public class pascal {
public static void main(String[] arg) {
Scanner sc = new Scanner(System.in);
System.out.print("please enter height of pascal triangle :");
int Heightchk = 0, Height = sc.nextInt();
if (Height > 0) {
MYarray PascalArray = new MYarray();
PascalArray.setLength(Height * 2 - 1);
PascalArray.IntilizeA(PascalArray.A);
if (Height == 1) {
PascalArray.printArray(PascalArray.A);
} else {
while (Heightchk < Height) {
PascalArray.printArray(PascalArray.A);
Heightchk += 1;
if (Heightchk < Height) {
PascalArray.reSet(PascalArray.B);
PascalArray.setElements(PascalArray.A, PascalArray.B);
PascalArray.printArray(PascalArray.B);
Heightchk += 1;
if (Heightchk < Height) {
PascalArray.reSet(PascalArray.A);
PascalArray.setElements(PascalArray.B, PascalArray.A);
}
}
}
}
} else {
System.out.println("Can't Draw pascal Triangle of this Height");
}
}
}
class MYarray {
String[] A, B;
void IntilizeA(String[] Array) {
Array[(Array.length - 1)/2] = "1";
}
void setLength(int length) {
A = new String[length];
B = new String[length];
for (int i = 0; i < A.length; i++) {
A[i] = "\t";
B[i] = "\t";
}
}
void reSet(String[] Array) {
for (int i = 0; i < Array.length; i++) {
Array[i] = "\t";
}
}
void printArray(String[] Array) {
for (String Element : Array) {
System.out.print(Element);
}
System.out.println();
System.out.println();
System.out.println();
}
void setElements(String[] from, String[] to) {
for (int i = 0; i < from.length; i++) {
if (from[i] != "\t") {
if (to[i - 1] == "\t") {
to[i - 1] = "0";
}
if (to[i + 1] == "\t") {
to[i + 1] = "0";
}
to[i - 1] = String.valueOf(Integer.valueOf(to[i - 1]) + Integer.valueOf(from[i]));
to[i + 1] = String.valueOf(Integer.valueOf(to[i + 1]) + Integer.valueOf(from[i]));
}
}
}
}
逻辑,我申请工作超好,但仍然有一个元素的对齐问题。 它给下面的输出:
please enter height of pascal triangle :5
1
1 1
1 2 1
1 3 3 1
,而它的输出应该是这样的:
please enter height of pascal triangle :5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
什么是我的逻辑问题。我怎样才能让它正确?
[帕斯卡三角正确的格式的Java(可能重复http://stackoverflow.com/questions/14371775/pascal -triangle-proper-formatting-java)和[Pascal三角形](http://stackoverflow.com/questions/15818341/pascal-triangle)和一些[230其他](http://stackoverflow.com/search q =帕斯卡三角形+ +是%3Aquestion)。 – Mogsdad
@Mogsdad其实我写了上面的代码,但得到适当的输出。 –