编写一个 Java 程序,使用 for 循环打印圣诞树星形图案。
package Shapes3;
import java.util.Scanner;
public class ChristmasTreeStar1 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter Chirstmas Tree Width & Height = ");
int width = sc.nextInt();
int height = sc.nextInt();
int space = width * height;
int i, j, k, n = 1;
System.out.println("Printing Chirstmas Tree Pattern of Stars");
for (int x = 1; x <= height; x++ )
{
for (i = n; i <= width; i++ )
{
for(j = space; j >= i; j--)
{
System.out.print(" ");
}
for(k = 1; k <= i; k++)
{
System.out.print("* ");
}
System.out.println();
}
n = n + 2;
width = width + 2;
}
for(i = 1; i <= height - 1; i++)
{
for(j = space - 3; j >= 0; j--)
{
System.out.print(" ");
}
for(k = 1; k <= height - 1; k++)
{
System.out.print("* ");
}
System.out.println();
}
}
}

此 Java 示例 允许输入一个字符,并使用函数打印给定字符的圣诞树图案。
package Shapes3;
import java.util.Scanner;
public class ChristmasTreeStar2 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter Christmas Tree Width & Height = ");
int width = sc.nextInt();
int height = sc.nextInt();
System.out.print("Enter Character for Christmas Tree Pattern = ");
char ch = sc.next().charAt(0);
System.out.println("Printing Christmas Tree Pattern");
ChristmasTreePattern(width, height, ch);
}
public static void ChristmasTreePattern(int width, int height, char ch)
{
int space = width * height;
int i, j, k, n = 1;
for (int x = 1; x <= height; x++ )
{
for (i = n; i <= width; i++ )
{
for(j = space; j >= i; j--)
{
System.out.print(" ");
}
for(k = 1; k <= i; k++)
{
System.out.print(ch + " ");
}
System.out.println();
}
n = n + 2;
width = width + 2;
}
for(i = 1; i <= height - 1; i++)
{
for(j = space - 3; j >= 0; j--)
{
System.out.print(" ");
}
for(k = 1; k <= height - 1; k++)
{
System.out.print(ch + " ");
}
System.out.println();
}
}
}
Please Enter Christmas Tree Width & Height = 9 5
Enter Character for Christmas Tree Pattern = *
Printing Christmas Tree Pattern
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * *
* * * *
* * * *
* * * *