gpt4 book ai didi

java - 绘制带有制表符和星号的 Java 圣诞树

转载 作者:行者123 更新时间:2023-11-30 08:02:24 28 4
gpt4 key购买 nike

我需要绘制一棵具有给定 n 行数的 java 圣诞树,但不是通常这样绘制的:

     *
***
*****
*******

但像这样,带有分隔标签:

             *
* *
* * *
* * * *

我目前的代码是这样的:

 public static void main(String[] args) {
int i =5;
for(;i!=0;i--) {
for(int j=0; j!=i; j++);
System.out.print("\t\t*");

我终于自己写了代码:

int x = 5;
for(int i=1; i<=x; i++)
{
for (int k=0; k<x-i; k++)
{
System.out.print("\t");
}
for (int j=0; j<i; j++)
{

System.out.print( "\t*\t" );
}
System.out.println("");
}

}

}

最佳答案

这将星星排成一行

public static void main(String[] args)
{

int n = 6;
int i = 0;
int pad = 7;
while (i < n)
{

String star = new String(new char[1 + i *2]).replace("\0", "*\t");
String space = new String(new char[1 + pad]).replace("\0", "\t");
System.out.printf(space + star + "\n");
++i;
--pad;
}

}

编辑这将根据您的演示替换它们

public static void main(String[] args)
{
final int it = 5;
int pad = it;
int i = 0;
String space;
while (i < it) {
String star = new String(new char[i + 1]).replace("\0", "*\t\t");

space = new String(new char[pad]).replace("\0", "\t");

System.out.printf(space + star + "\n");
++i;

--pad;

}

}

完成for循环

public static void main(String[] args)
{
//final int it = 5;
int size;
size = 5;

for( int i = 1; i < size; ++i)
{
String star = "";
for (int p = size; p > i; --p)
{
star += "\t";
}
for (int j = 0; j < i; ++j)
{
star += "*\t\t";
}

System.out.println(star);


}

}

另一种只使用 2 个循环的解决方案

public static void main(String[] args)
{
//final int it = 5;
int size;
size = 5;
List<String> pad = new ArrayList<String>();
pad.addAll(Arrays.asList("\t","\t","\t","\t","\t"));
for( int i = 1; i < size; ++i)
{
String star = "";
//Pattern p = Pattern.compile("([)|(,)|(])");
star += pad.toString().replaceAll("\\[|\\]|,", "");
for (int j = 0; j < i; ++j)
{
star += "*\t\t";
}
pad.remove(pad.size()-1);
System.out.println(star);

}

}

关于java - 绘制带有制表符和星号的 Java 圣诞树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36964918/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com