改变我的代码打印方式

时间:2014-10-13 23:54:58

标签: java formatting string-formatting

我需要帮助弄清楚如何改变我的代码打印方式,我明白它会做一些处理

的事情

n,n-1,n-2,...等间距,但我该怎么做才能得到这个

        1
      2 1
    3 2 1
... 3 2 1

而不是

  1
  1 2
  1 2 3
  1 2 3...



//A program that displays the pattern of a number entered in increasing order

import java.util.Scanner;

public class DisplayPattern  
{  
   public static void main(String ar[])  
   {
      //Initialize Scanner
      Scanner input = new Scanner(System.in);
    
      //Get user input/ start loop
      while (true)
      {
         //Receive user input
         System.out.println("Enter a positive integer to display pattern: ");
         int x = input.nextInt();
         
         //Show user output  
         displayPattern(x);
         
      //Continuation of loop
         System.out.println("Do you want to continue (Y/N)?");
         String s = input.nextLine();
         s = input.nextLine();
         s = s.toLowerCase();
         if (s.charAt(0) == 'n')
            break;
      }           
   }  
   
   public static void displayPattern(int n)  
   {
      //Create pyramid of numbers with increasing order  
      for(int i=1;i<=n;i++)  
      {  
         for(int j=i;j>0;j--)  
         { 
               System.out.print(" "+j);  
         }  
            System.out.print("\n");  
      }  
   }  
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您需要确保为不首先打印的数字创建空格,因此我们始终使用用户输入启动内部循环。

这应该适合你:

public static void displayPattern(int n) {
    // Create pyramid of numbers with increasing order
    for (int i = 1; i <= n; i++) {
        for (int j = n; j > 0; j--) {
            if (j > i) {
                System.out.print("  ");
            } else {
                System.out.print(" " + j);
            }
        }
        System.out.print("\n");
    }
}