java - 如何在网格中水平和垂直多次打印相同的输出?
问题描述
我可以打印一棵不同大小的松树,但是如何在网格中打印它旁边和下面的精确副本,仅使用 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("___");
}
}
}
解决方案
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))
等。
确保在处理额外的事情之前完成任务。
推荐阅读
- awk - 用特定值替换子字符串的 awk 命令
- css - 使用 css attr() 函数计算 sass 中的 css 顶部
- python - 模拟请求发布响应 __dict__ 和 status_code python
- r - 在 R arules 中,如何有效地将集值数据转换为项集成员数据?
- html - TestCafe:创建一个选择器,其中有多个跨度的 div
- .net-core - 在 Debian 上使用 .Net Core 的 Jenkins 管道失败 UnitTests
- xamarin - 在多个设备之间具有相同的控制宽度
- angular - NPM 构建挂在 azure dev ops 中
- python - 如何动态地水平堆叠 gif 以在 python 中创建一个 gif?
- python - pyspark groupby 并创建包含其他列字典的列