2015-11-23 95 views
0

這裏是輸出帕斯卡三角形的一些代碼,它顯示了三角形的所有線條。例如,如果用戶輸入是5,那麼它將輸出如下:帕斯卡爾三角形 - 只打印第n行

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

但我只是想輸出最後一行。所以,對於5,只有1 4 6 4 1.我很難完成這個,雖然它很容易,我知道。任何幫助表示讚賞。

import java.util.Scanner; 

public class PascalsTriangle { 
    public static void computeRow(int n) { 
     int counter; 
     for (int i = 0; i < n; i++) { 
      for (int j = 0; j <= i; j++) { 
       System.out.print(pascalValue(i, j) + " "); 
      } 
      System.out.println(); 
     } 
    } 

    public static int pascalValue(int i, int j) { 
     if (j == 0) { 
      return 1; 
     } else if (j == i) { 
      return 1; 
     } else { 
      return pascalValue(i - 1, j - 1) + pascalValue(i - 1, j); 
     } 
    } 

    public static void main(String[] args) { 
     Scanner scanner = new Scanner(System.in); 
     System.out.print("Which line number of Pascal's Triangle? "); 
     int row = scanner.nextInt(); 
     System.out.print("Line " +row+" of Pascal's Triangle:\n"); 
     computeRow(row); 
    } 
} 
+1

嘗試把的條件之前打印聲明。你會使用哪種情況? –

+0

我在computeRow中的打印語句之前已經嘗試過各種if語句,但似乎無法找到按預期工作的語句。 –

回答

2

更改computeRow()方法包括您要打印的三角形的特定線路上的檢查。在你的情況,你只需要打印的最後一行,這將使最後迭代外for循環的過程中出現:

public static void computeRow(int n) { 
    int counter; 
    for (int i = 0; i < n; i++) { 
     // only output the line if it be the last one 
     if (i == n-1) { 
      for (int j = 0; j <= i; j++) { 
       System.out.print(pascalValue(i, j) + " "); 
      } 
      System.out.println(); 
     } 
    } 
} 

public static void main(String[] args) { 
    computeRow(5); 
} 

輸出:

Line 5 of Pascal's Triangle: 
1 4 6 4 1 
+0

謝謝!這很好。我從來沒有想過這樣。再次感謝Tim。 –