java - java中带茎的星形图案左帕斯卡箭头
问题描述
*
**
***
******************
*******************
******************
***
**
*
我正在尝试在 Java 中打印此模式。它用于分配,我们必须使用 if,else 语句来打印上述模式。
class fulldesign7
{
public static void main(String[] args)
{
int star=0;
int space=5;
for(int i=1;i<=9;i++)
{
if(i<=5)
{
space--;
star++;
}
else if(i==4||i==5||i==6)
{
star=star+10;
}
else
{
space++;
star--;
}
for(int j=1;j<=space;j++)
{
System.out.print(" ");
}
for(int k=1;k<=star;k++)
{
System.out.print("*");
}
System.out.println();
}
}
}
到目前为止,这是我想出的。但是 if 语句和 else 语句发生冲突。
解决方案
我认为您可以将箭头分为点和尾,我的意思是首先尝试弄清楚如何打印:
*
**
***
****
*****
****
***
**
*
然后在第 3、4 和 5 行为尾巴添加星星
因此,首先创建一个方法来打印给定多个空格和星号的行,如果我们将尾部添加到它:
private static void printLine(int spaces, int stars, boolean addTail) {
for (int i = 0; i < spaces; i++) {
System.out.print(" ");
}
for (int i = 0; i < stars; i++) {
System.out.print("*");
}
if (addTail) {
System.out.println("**************");
} else {
System.out.println();
}
}
然后添加星号并删除直到第 5 行的空格,然后为其余行反转。在第 3、4 和 5 行添加尾部:
public static void main(String args[]) {
int spaces = 5;
int stars = 0;
for (int line = 0; line < 9; line++) {
if (line<5) {
spaces --;
stars ++;
} else {
spaces ++;
stars --;
}
boolean addTail = line >= 3 && line <=5;
printLine(spaces, stars, addTail);
}
}
注意:您也可以尝试变得更聪明,并注意两件事:
- 空格数是 (line - 4) 的绝对值
- 星数总是 5 减去空格数
所以main也可以这样写:
public static void main(String args[]) {
for (int line = 0; line < 9; line++) {
int spaces = Math.abs(line - 4);
boolean addTail = line >= 3 && line <=5;
printLine(spaces, 5-spaces, addTail);
}
}
推荐阅读
- docker - Nginx 无法从 docker-compose 找到上游
- javascript - 在wordpress中强制加载iframe不起作用
- php - php水印文本定位与拖放jquery
- tensorflow - MNIST“1”和“5”的二元分类准确率变好了吗?
- java - 如何从 Collections 中获取 shuffle() 以不修改列表中的每个数组?
- javascript - 我想在 JS 中创建一个自定义数组
- html - 为什么 first-of-type 不针对我的第一个脚注?
- c++ - 在不使用数组和字符串的情况下从重新排列数字中找到最小和最大数字
- java - 具有由多个其他类 SpringBoot 重用的数据结构的类
- excel - Flutter - 导出 csv 在 Excel 中读取为乱码