首页 > 解决方案 > 如何在网格中水平和垂直多次打印相同的输出?

问题描述

我可以打印一棵不同大小的松树,但是如何在网格中打印它旁边和下面的精确副本,仅使用 for 循环?该项目使用扫描仪,以便用户可以改变每棵树的大小和部分的数量。项目的最后一部分允许用户选择要打印的树的数量,水平(彼此相邻)和垂直(在其下方)。确切的措辞和示例:程序使用第三个输入来打印许多树。例如:当 NUM_TREES 为 3 时,将打印 3x3 的树网格。任何提示或提示都是有帮助的,谢谢。

这是我必须得到一棵树的代码:

import java.util.Scanner;

public class PineTreeUpgrade {
    static int numSections;
    static int sectionSize;

    public static void main(String[] args) {
        askTheUserForInput();
        System.out.println();
        System.out.println("Here is your amazing creation! How artistic!");
        printTree();
        printStem();
    }

    public static void askTheUserForInput() {
        Scanner userInput = new Scanner(System.in);
        System.out.println("Hello, user!");
        System.out.println("How many section would you like in your pine tree?");
        numSections = userInput.nextInt();
        System.out.println("Great! How big would you like each section to be?");
        sectionSize = userInput.nextInt();    
    }

    public static void printTree() {
        for (int k = 0; k < numSections; k++) {
            //prints the next section, each one increasing in size
            for(int i = 0; i < sectionSize; i++) {
                //prints the spaces and number of stars in each section
                for (int j = i; j < (sectionSize - 1) + (numSections - 1) - k; j++){
                    System.out.print(" ");
                }

                System.out.print("/");

                for (int j = 0; j < i + k; j++) {
                    System.out.print("*");
                }

                System.out.print("*");

                for (int j = 0; j < i + k; j++) {
                    System.out.print("*");
                }

                System.out.println("\\");

            }
        }

    }

    public static void printStem() {
        for(int i = 0; i < 2; i++) {

            for (int j = 0; j < (sectionSize - 1) + (numSections -1) + 1; j++) {
                System.out.print(" ");
            }

            System.out.println("|");

        }

        for (int i = 0; i < 1; i++) {

            for (int j = 0; j < (sectionSize - 1) + (numSections -1); j++) {
                System.out.print(" ");
            }

            System.out.print("___");

        }
    }
}

标签: javafor-loop

解决方案


width_of_double_pine_tree = 2 * width_of_single_pine_tree + buffer_between_trees

For 循环不必定义变量,它们可以使用现有的变量。

int j = 0;
for(; j < (width_of_double_pine_tree - (width_of_single_pine_tree + buffer_between_trees)); j++)
//this is your first tree
for(; j < (width_of_double_pine_tree - width_of_single_pine_tree); j++)
//this is your buffer (S.o.p spaces)
for(; j < (width_of_double_pine_tree); j++)
//this is your second tree

你的画布总是一个矩形,你从中减去你没有使用的边缘空间,带空格的空白空间(标签毁了一切,因为它们不统一,在所有东西中都使用空格!)

使用您的 i 变量来跟踪您当前在画布上绘制的高度,以便您可以在松针和树干中进行数学计算。对于第二棵树,在数学部分,将 j 偏移 buffer_between_trees 和 width_of_single_treeif(i < (j + buffer + width))等。

确保在处理额外的事情之前完成任务。


推荐阅读