Как напечатать один и тот же вывод несколько раз по горизонтали и вертикали в сетке? - PullRequest
0 голосов
/ 21 октября 2018

Я могу напечатать одну сосну разных размеров, но как мне распечатать точную копию этого рядом с ним и под ним, в сетке, используя только для петель?В этом проекте используется сканер, поэтому пользователь может изменять размер и количество разделов каждого дерева.Последняя часть проекта позволяет пользователю выбрать количество деревьев для печати по горизонтали (рядом друг с другом) и по вертикали (под ним).Точная формулировка и пример: Программа использует третий ввод для печати нескольких деревьев.Пример: Когда NUM_TREES равен трем, печатается сетка деревьев 3х3.Любые советы или подсказки полезны, спасибо.

Вот код, который я должен получить для одного дерева:

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

        }
    }
}

Ответы [ 2 ]

0 голосов
/ 21 октября 2018
import java.util.Scanner;

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

    public static void main(String[] args) {
        askTheUserForInput();
        System.out.println();
        System.out.println("Here is your amazing creation! How artistic!");
        for(int x = 0; x < gridSize; x++){
            printTree();
            printStem();
            System.out.println();
        }
    }

    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();
        System.out.println("What grid size do you want?");
        gridSize = 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 x = 0; x < gridSize; x++){
                    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.print("\\");
                    int width = 2 * (sectionSize + numSections - 1) + 1;
                    if(x != gridSize - 1){
                        for(int y = sectionSize + numSections + k + i; y < width; y++)
                            System.out.print(" ");
                        System.out.print(" ");
                    }
                }
                System.out.println();

            }
        }

    }

    public static void printStem() {
        for(int i = 0; i < 2; i++) {
            for(int x = 0; x < gridSize; x++){
                for (int j = 0; j < (sectionSize - 1) + (numSections -1) + 1; j++)
                    System.out.print(" ");

                System.out.print("|");

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

            System.out.println();

        }

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

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

                System.out.print("___");

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

        }
    }
}
0 голосов
/ 21 октября 2018

width_of_double_pine_tree = 2 * width_of_single_pine_tree + buffer_between_trees

Для циклов не нужно определять переменную, они могут использовать существующую.

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_tree if(i < (j + buffer + width)) и т. Д.

Убедитесь, что вы выполнили задание, прежде чем заняться дополнительными вещами.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...