我寫我自己的邏輯來打印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其實我寫了上面的代碼,但得到適當的輸出。 –