[英]Removing leading spaces on Pascals Triangle
我在下面有一些示例代碼來打印Pascals Triangle。 (我在掃描儀上使用測試用例= 14)代碼可以工作,但結果中有前導空格。 如何刪除三角形前面的這些空格?
import java.util.Scanner;
public class PascalsTriangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int rows = input.nextInt();
for(int i = 0;i<rows;i++) {
int pascal = 1;
System.out.format("%"+(rows-i)*2+"s","");)
for(int j=0;j<=i;j++) {
System.out.format("%4d", pascal);
pascal = pascal* (i - j) / (j + 1);
}
System.out.println();
}
}
}
我認為正在發生的事情是你輸出4個字符'塊'中的數字,這條線照看那部分;
String output = String.format("%4d", number);
以下將輸出“框”左側的數字 - 盡管空格現在將是尾隨的。
String output = String.format("%-4d", number);
這一切都取決於你將要使用的n的最大值。 例如,你可以決定每個數字將占用4個字符(如果所有數字都是9999或更少 - 實際上,Pascal的三角形有20行,你至少需要5個字符)。 然后,您需要調整在三角形的每一行中打印出的空格數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.