使用递归在Java中以正确格式打印菱形图案

我的程序从文件中读取值,并使用递归方法根据这些值打印星号模式。 我只是在让一切正常排队时遇到问题。

输出应该如下所示:

* * * * * * * * * 

关于输出的格式,方向是:

“请注意,图案围绕中心线对称(垂直)对齐。图案应在每条线(水平)上对称排列,并提示:使用线值来帮助空间。”

但我的输出看起来像这样:

 * * * * * * * * * 

我用来获取这种模式的代码:

 public static void makePattern(int thisRow, int num) { if(thisRow >= num) { for(int i = 0; i < num; i++) { System.out.print(" " + "*" + " "); } System.out.println(); } else { for(int i = 0; i < thisRow; i++) { System.out.print(" " + "*" + " "); } System.out.println(); makePattern(thisRow + 1, num); for(int i = 0; i < thisRow; i++) { System.out.print(" " + "*" + " "); } System.out.println(); } } 

我的主要方法:

 import java.util.Scanner; import java.io.*; public class Program3 { public static void main(String[] args) throws Exception { int num = 0; int thisRow = 1; java.io.File file = new java.io.File("../instr/prog3.dat"); Scanner fin = new Scanner(file); while(fin.hasNext()) { num = fin.nextInt(); if(num >=0 && num <= 25) makePattern(thisRow, num); System.out.println(); } fin.close(); } 

有关如何编辑我的代码以使我的输出的任何建议看起来像我包含的示例模式?

让我们先分析输出!

第一步是分析输出

在此处输入图像描述

结论:

  • 每行的字符总数始终为n (= 3)
  • 空格数具有以下模式:

    第1行 3 – 1个空格
    第2行 3 – 2个空格
    第3行 3 – 3个空格
    第4行 4 – 3个空格
    第5行 5 – 3个空格

    所以

     if(num < thisRow) { numberOfSpaces = thisRow - num; } else { numberOfSpaces = num - thisRow; } 
  • 星数总是[ n - 空格数 ]

    所以

     int numberOfStars = num - numberOfSpaces; 
  • 并且递归应该在第6行结束,即当前行号为n * 2时

    所以递归方法中的返回条件应该是

     if(thisRow == num * 2) return; 

最终守则:把问题放在一起

当我们把peices放在一起时,我们得到:

  public static void makePattern(int thisRow, int num) { //the termination condition if(thisRow == num * 2) return; //the number of spaces int numberOfSpaces = 0; if(num < thisRow) { numberOfSpaces = thisRow - num; } else { numberOfSpaces = num - thisRow; } //the number of stars int numberOfStars = num - numberOfSpaces; //compose the string before printing it StringBuffer outputBuffer = new StringBuffer(num); for (int i = 0; i < numberOfSpaces; i++){ outputBuffer.append(" "); } for (int i = 0; i < numberOfStars; i++){ outputBuffer.append("* "); } //print the string System.out.println(outputBuffer.toString()); //recursion makePattern(thisRow + 1, num); } 

这是使用递归技术打印菱形图案的代码。

  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class patternRecursion { static int n,k; public static void main(String[] args) throws IOException{ try(Scanner s = new Scanner(System.in)){ n=Integer.parseInt(reader.readLine()); k=n-1; printPattern(n); } } public static void printChar(int m,char c){ if(m==0) return; try{ printChar(m-1,c); System.out.print(c); }catch(StackOverflowError s){return;} } public static void printPattern(int m){ if(m==0){ return ; }else{ printChar(m-1,' '); printChar(nm,'#'); printChar(n-m+1,'#'); System.out.println(); printPattern(m-1); printChar(m,' '); printChar(km,'#'); printChar(k-m+1,'#'); System.out.println(); } } 

}