简体   繁体   English

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

[英]Printing Diamond Pattern in Correct Format in Java using Recursion

My program reads in values from a file and uses a recursive method to print patterns of asterisks based on those values. 我的程序从文件中读取值,并使用递归方法基于这些值打印星号模式。 I'm just having a problem getting everything to line up properly. 我只是遇到问题,无法正确排列所有内容。

The output is supposed to look like this: 输出应该看起来像这样:

    *
  *   *
*   *   *
  *   *  
    *

Regarding the format of the output, the directions are: 关于输出的格式,说明如下:

"Note that the pattern is aligned symmetrically (vertically) about the center line. The pattern should be aligned symmetrically on each line (horizontally) as well- hint: use the line value to help space." “请注意,图案围绕中心线对称(垂直)对齐。图案应该在每条线上(水平)对称对齐,这提示:使用线值可以帮助间距。”

But my output looks like this: 但是我的输出看起来像这样:

*
*  *
*  *  *
*  *
*

The code I'm using to get this pattern: 我用来获取此模式的代码:

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();
    }
}

Also my main method: 还有我的主要方法:

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();

    }

Any suggestions on how to edit my code to make my output appear like the example pattern I included? 关于如何编辑代码以使输出看起来像我包括的示例模式的任何建议?

Let's analyse the output first!! 让我们先分析输出!!

First step is to analyse the output 第一步是分析输出

在此处输入图片说明

Conclusions: 结论:

  • The total number of characters on every line is always n (=3) 每行的字符总数始终为n (= 3)
  • Number of Spaces has the following pattern: Number of Spaces具有以下模式:

    1st line 3 - 1 spaces 第一线 3 - 1个空间
    2nd line 3 - 2 spaces 第二行 2-3 空格
    3rd line 3 - 3 spaces 第三行 3-3个空格
    4th line 4 - 3 spaces 第四行 4-3个空格
    5th line 5 - 3 spaces 第5行 3-5个空格

    So 所以

     if(num < thisRow) { numberOfSpaces = thisRow - num; } else { numberOfSpaces = num - thisRow; } 
  • Number of Stars is always [ n - the number of spaces ] 星数始终为[ n-空格数 ]

    So 所以

     int numberOfStars = num - numberOfSpaces; 
  • And the recursion should end on the 6th line, ie when current line number is n*2 并且递归应该在第6行结束,即当前行号为n * 2时

    So the return condition in your recursive method should be 因此,递归方法中的返回条件应为

     if(thisRow == num * 2) return; 



Final Code : Putting the peices together 最终代码:将调味料放在一起

When we put the peices together, we get: 当我们把调味料放在一起时,我们得到:

    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);
   }

This is code for printing diamond shaped pattern using recursion technique. 这是使用递归技术打印菱形图案的代码。

    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(n-m,'#');
        printChar(n-m+1,'#');
           System.out.println();
           printPattern(m-1);
         printChar(m,' ');
         printChar(k-m,'#');
         printChar(k-m+1,'#');
            System.out.println();
         }

    }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM